Subject: Re: [PATCH v3 07/18] rerere: stop looping unnecessarily

From: Junio C Hamano <[email-masked]>
Date: Fri, 24 Jul 2015 13:06:49 -0700

Junio C Hamano <[email-masked]> writes:

> handle_cache() loops 3 times starting from an index entry that is
> unmerged, while ignoring an entry for a path that is different from
> what we are looking for.
>
> As the index is sorted, once we see a different path, we know we saw
> all stages for the path we are interested in.  Just loop while we
> see the same path and then break, instead of continuing for 3 times.
>
> Signed-off-by: Junio C Hamano <[email-masked]>
> ---
>  rerere.c | 17 +++++++----------
>  1 file changed, 7 insertions(+), 10 deletions(-)
>
> diff --git a/rerere.c b/rerere.c
> index 4c45f55..7b1419c 100644
> --- a/rerere.c
> +++ b/rerere.c
> @@ -329,24 +329,21 @@ static int handle_cache(const char *path, unsigned char *sha1, const char *outpu
>  		return -1;
>  	pos = -pos - 1;
>  
> -	for (i = 0; i < 3; i++) {
> +	while (pos < active_nr) {
>  		enum object_type type;
>  		unsigned long size;
> -		int j;
>  
> -		if (active_nr <= pos)
> -			break;
>  		ce = active_cache[pos++];
>  		if (ce_namelen(ce) != len || memcmp(ce->name, path, len))
> -			continue;
> -		j = ce_stage(ce) - 1;
> -		mmfile[j].ptr = read_sha1_file(ce->sha1, &type, &size);
> -		mmfile[j].size = size;
> +			break;
> +		i = ce_stage(ce) - 1;
> +		mmfile[i].ptr = read_sha1_file(ce->sha1, &type, &size);
> +		mmfile[i].size = size;

If the conflicted index has multiple stage #1 entries, this will leak
what was previously read.  As the array is initialized to NULLs, perhaps

	i = ce_stage(ce) - 1;
        if (!mmfile[i].ptr) {
		mmfile[i].ptr = read_sha1_file(ce->sha1, &type, &size);
                mmfile[i].size = size;
	}

should be sufficient.  This does change the semantics, in that we
used to use the last stage #1 entry as the common ancestor when
doing the plain-vanilla three-way merge, but with the leak fix, we
will use the first stage #1 entry.  But it does not change it in
any meaningful way---we are using only one of multiple stage #1
entries arbitrarily picked either way.

>  	}
> -	for (i = 0; i < 3; i++) {
> +	for (i = 0; i < 3; i++)
>  		if (!mmfile[i].ptr && !mmfile[i].size)
>  			mmfile[i].ptr = xstrdup("");
> -	}
> +
>  	/*
>  	 * NEEDSWORK: handle conflicts from merges with
>  	 * merge.renormalize set, too