Re: [PATCH 01/14] strbuf: introduce strbuf_prefixf()
- From
Eric Sunshine <sunshine@sunshineco.com>
- Date
- Dec 3, 2014, 20:10 UTC
- Message-ID
- <CAPig+cS6Z=UW80sn6ru15W29Vko-f2g4CUq0EQtWGU7ZjoJcog@mail.gmail.com>
- In-Reply-To
- <20141203051016.GK6527@google.com>
On Wed, Dec 3, 2014 at 12:10 AM, Jonathan Nieder <jrnieder@gmail.com> wrote:
Show 39 quoted lines
> When preparing an error message in a strbuf, it can be convenient
> to add a formatted string to the beginning:
>
> if (transaction_commit(&t, err)) {
> strbuf_prefixf(err, "cannot fetch '%s': ", remotename);
> return -1;
> }
>
> The new strbuf_prefixf is like strbuf_addf, except it writes its
> result to the beginning of a strbuf instead of the end.
>
> The current implementation uses strlen(strfmt(fmt, ...)) extra bytes
> at the end of the strbuf as temporary scratch space for convenience
> and simplicity. A later patch can optimize if needed.
>
> Signed-off-by: Jonathan Nieder <jrnieder@gmail.com>
> ---
> diff --git a/strbuf.c b/strbuf.c
> index 0346e74..3f4aaa3 100644
> --- a/strbuf.c
> +++ b/strbuf.c
> @@ -219,6 +219,22 @@ void strbuf_addf(struct strbuf *sb, const char *fmt, ...)
> va_end(ap);
> }
>
> +void strbuf_prefixf(struct strbuf *sb, const char *fmt, ...)
> +{
> + va_list ap;
> + size_t pos, len;
> +
> + pos = sb->len;
> +
> + va_start(ap, fmt);
> + strbuf_vaddf(sb, fmt, ap);
> + va_end(ap);
> +
> + len = sb->len - pos;
> + strbuf_insert(sb, 0, sb->buf + pos, len);
> + strbuf_remove(sb, pos + len, len);Would a strbuf_setlen(sb, pos), rather than strbuf_remove(), make it clearer to the reader that this is merely performing a truncation?
Show 5 quoted lines
> +} > + > static void add_lines(struct strbuf *out, > const char *prefix1, > const char *prefix2,