Subject: Re: [PATCH 3/3] --format=pretty: avoid calculating expensive expansions twice

From: Junio C Hamano <[email-masked]>
Date: Sun, 11 Nov 2007 02:29:12 -0800

René Scharfe <[email-masked]> writes:

> +static int add_again(struct strbuf *sb, struct chunk *chunk)
> +{
> +	if (chunk->len) {
> +		strbuf_adddup(sb, chunk->off, chunk->len);
> +		return 1;
> +	}
> +
> +	/*
> +	 * We haven't seen this chunk before.  Our caller is surely
> +	 * going to add it the hard way now.  Remember the most likely
> +	 * start of the to-be-added chunk: the current end of the
> +	 * struct strbuf.
> +	 */
> +	chunk->off = sb->len;
> +	return 0;
> +}
> +
>  static void parse_commit_header(struct format_commit_context *context)
>  {
>  	const char *msg = context->commit->buffer;
> @@ -447,15 +469,21 @@ static void format_commit_item(struct strbuf *sb, const char *placeholder,
>  		strbuf_addstr(sb, sha1_to_hex(commit->object.sha1));
>  		return;
>  	case 'h':		/* abbreviated commit hash */
> +		if (add_again(sb, &c->abbrev_commit_hash))
> +			return;
>  		strbuf_addstr(sb, find_unique_abbrev(commit->object.sha1,
>  		                                     DEFAULT_ABBREV));
> +		c->abbrev_commit_hash.len = sb->len - c->abbrev_commit_hash.off;
>  		return;

Brilliant.  Doubly brilliant is the adddup abstraction that does
not suffer from underlying strbuf being reallocated.

Me likee..