Subject: Re: [PATCH] optimize path_relative()

From: Clemens Buchacher <[email-masked]>
Date: Fri, 4 Jun 2010 09:50:34 +0200

On Fri, Jun 04, 2010 at 09:44:43AM +0200, Clemens Buchacher wrote:

> +static const char *path_relative(const char *in, int len,
> +				 struct strbuf *sb, const char *prefix,
> +				 int prefix_len)
>  {
> +	int off, i;
> +
>  	if (len < 0)
>  		len = strlen(in);
>  	if (prefix && prefix_len < 0)
>  		prefix_len = strlen(prefix);
>  
> -	strbuf_setlen(out, 0);
> -	strbuf_grow(out, len);
> +	off = 0;
> +	i = 0;
> +	while (i < prefix_len && i < len && prefix[i] == in[i]) {
> +		if (prefix[i] == '/')
> +			off = i + 1;
> +		i++;
> +	}
> +	in += off;
> +	len -= off;
>  
> -	if (prefix_len > 0) {
> -		int off = 0, i = 0;
> -		while (i < prefix_len && i < len && prefix[i] == in[i]) {
> -			if (prefix[i] == '/')
> -				off = i + 1;
> -			i++;
> -		}
> -		in += off;
> -		len -= off;
> +	if (i == prefix_len)
> +		return in;
>  
> -		while (i < prefix_len) {
> -			if (prefix[i] == '/')
> -				strbuf_addstr(out, "../");
> -			i++;
> -		}
> +	strbuf_reset(sb);
> +	strbuf_grow(sb, len);
> +
> +	while (i < prefix_len) {
> +		if (prefix[i] == '/')
> +			strbuf_addstr(sb, "../");
> +		i++;
>  	}

By the way, I noticed that we rely on the fact that a non-empty
prefix ends with '/'. Is that ok?

> -	strbuf_add(out, in, len);
> +	strbuf_add(sb, in, len);
>  
> -	return out->buf;
> +	return sb->buf;
>  }