replace strbuf_expand()
cover replace strbuf_expand()
strbuf_expand() is used to interpolate placeholders that start with a percent sign (%) in strings. It invokes a callback function to handle those placeholders, expands "%%" to "%" itself and copies unrecognized placeholders verbatim. Context info for the callback needs to be passed in via a void pointer, e.g. to a custom struct.
There is a better, simpler way: Use a loop to iterate over placeholders and access variables directly, without the need to take a detour through a context struct. This series converts the callers of strbuf_expand() to use the new helper strbuf_expand_step(), removing the overhead that comes with using a callback.
pretty: factor out expand_separator()
strbuf: factor out strbuf_expand_step()
replace strbuf_expand_dict_cb() with strbuf_expand_step() replace strbuf_expand() with strbuf_expand_step()
strbuf: simplify strbuf_expand_literal_cb()
builtin/branch.c | 13 +----- builtin/cat-file.c | 35 +++++++-------- builtin/ls-files.c | 109 +++++++++++++++++++-------------------------- builtin/ls-tree.c | 107 +++++++++++++++++--------------------------- convert.c | 22 +++++---- daemon.c | 61 ++++++++----------------- ll-merge.c | 32 +++++++------ pretty.c | 99 ++++++++++++++++++++++------------------ strbuf.c | 58 +++++------------------- strbuf.h | 57 ++++-------------------- 10 files changed, 228 insertions(+), 365 deletions(-)
--
2.41.0
PATCH 1/5 pretty: factor out expand_separator()
Deduplicate the code for setting the options "separator" and "key_value_separator" by moving it into a new helper function, expand_separator().
--- pretty.c | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-)
pretty.c +13 -14
@@ -1250,6 +1250,17 @@ static int format_trailer_match_cb(const struct strbuf *key, void *ud)return 0 ; } +static struct strbuf *expand_separator (struct strbuf *sb, +const char *argval,size_t arglen) +{ +char *fmt =xstrndup (argval, arglen); + +strbuf_reset (sb); +strbuf_expand (sb, fmt, strbuf_expand_literal_cb,NULL ); +free (fmt); +return sb; +} + int format_set_trailers_options(struct process_trailer_options *opts, struct string_list *filter_list, struct strbuf *sepbuf,
@@ -1278,21 +1289,9 @@ int format_set_trailers_options(struct process_trailer_options *opts, opts->filter_data = filter_list; opts->only_trailers =1 ; }else if (match_placeholder_arg_value (*arg,"separator" , arg, &argval, &arglen)) { -char *fmt; - -strbuf_reset (sepbuf); - fmt =xstrndup (argval, arglen); -strbuf_expand (sepbuf, fmt, strbuf_expand_literal_cb,NULL ); -free (fmt); - opts->separator = sepbuf; + opts->separator =expand_separator (sepbuf, argval, arglen); }else if (match_placeholder_arg_value (*arg,"key_value_separator" , arg, &argval, &arglen)) { -char *fmt; - -strbuf_reset (kvsepbuf); - fmt =xstrndup (argval, arglen); -strbuf_expand (kvsepbuf, fmt, strbuf_expand_literal_cb,NULL ); -free (fmt); - opts->key_value_separator = kvsepbuf; + opts->key_value_separator =expand_separator (kvsepbuf, argval, arglen); } else if (!match_placeholder_bool_arg(*arg, "only", arg, &opts->only_trailers) && !match_placeholder_bool_arg(*arg, "unfold", arg, &opts->unfold) && !match_placeholder_bool_arg(*arg, "keyonly", arg, &opts->key_only) &&
--
2.41.0
PATCH 2/5 strbuf: factor out strbuf_expand_step()
In reply to René ScharfeExtract the part of strbuf_expand that finds the next placeholder into a new function. It allows to build parsers without callback functions and the overhead imposed by them.
--- builtin/branch.c | 13 ++----------- strbuf.c | 28 ++++++++++++++-------------- strbuf.h | 8 ++++++++ 3 files changed, 24 insertions(+), 25 deletions(-)
builtin/branch.c +2 -11
@@ -366,17 +366,8 @@ static const char *quote_literal_for_format(const char *s)static struct strbuf buf =STRBUF_INIT ;strbuf_reset (&buf); -while (*s) { -const char *ep =strchrnul (s,'%' ); -if (s < ep) -strbuf_add (&buf, s, ep - s); -if (*ep =='%' ) { -strbuf_addstr (&buf,"%%" ); - s = ep +1 ; - }else { - s = ep; - } - } +while (strbuf_expand_step (&buf, &s)) +strbuf_addstr (&buf,"%%" );return buf.buf; }
strbuf.c +14 -14
@@ -415,19 +415,24 @@ void strbuf_vaddf(struct strbuf *sb, const char *fmt, va_list ap)strbuf_setlen (sb, sb->len + len); } +int strbuf_expand_step (struct strbuf *sb,const char **formatp) +{ +const char *format = *formatp; +const char *percent =strchrnul (format,'%' ); + +strbuf_add (sb, format, percent - format); +if (!*percent) +return 0 ; + *formatp = percent +1 ; +return 1 ; +} +void strbuf_expand (struct strbuf *sb,const char *format,expand_fn_t fn,void *context) { -for (;;) { -const char *percent; +while (strbuf_expand_step (sb, &format)) {size_t consumed; - percent =strchrnul (format,'%' ); -strbuf_add (sb, format, percent - format); -if (!*percent) -break ; - format = percent +1 ; -if (*format =='%' ) {strbuf_addch (sb,'%' ); format++;
@@ -1022,12 +1027,7 @@ void strbuf_addftime(struct strbuf *sb, const char *fmt, const struct tm *tm,* we want for %z, but the computation for %s has to convert to number * of seconds. */ -for (;;) { -const char *percent =strchrnul (fmt,'%' ); -strbuf_add (&munged_fmt, fmt, percent - fmt); -if (!*percent) -break ; - fmt = percent +1 ; +while (strbuf_expand_step (&munged_fmt, &fmt)) {switch (*fmt) {case '%' :strbuf_addstr (&munged_fmt,"%%" );
strbuf.h +8 -0
@@ -371,6 +371,14 @@ size_t strbuf_expand_dict_cb(struct strbuf *sb,const char *placeholder, void *context); +/** +* If the string pointed to by `formatp` contains a percent sign ("%"), +* advance it to point to the character following the next one and +* return 1, otherwise return 0. Append the substring before that +* percent sign to `sb`, or the whole string if there is none. +*/ +int strbuf_expand_step (struct strbuf *sb,const char **formatp); +/** * Append the contents of one strbuf to another, quoting any * percent signs ("%") into double-percents ("%%") in the
--
2.41.0
Re: [PATCH 2/5] strbuf: factor out strbuf_expand_step()
strbuf.c void strbuf_vaddf(struct strbuf *sb, const char *fmt, va_list ap) · line 421
Quoted 12 lines · René Scharfe
strbuf.c +4
-0@@ -415,19 +415,24 @@ void strbuf_vaddf(struct strbuf *sb, const char *fmt, va_list ap)strbuf_setlen (sb, sb->len + len); } +int strbuf_expand_step (struct strbuf *sb,const char **formatp) +{ +const char *format = *formatp; +const char *percent =strchrnul (format,'%' );
Can format be NULL here? Obviously formatp is never NULL since it is &s, but we guarded the while loop in the pre-image with while (*s) and I am not sure that **formatp is always non-NULL here.
Thanks,
Taylor
Re: [PATCH 2/5] strbuf: factor out strbuf_expand_step()
Am 19.06.23 um 18:10 schrieb Taylor Blau:
Quoted 9 lines · René Scharfe
Quoted 8 lines
strbuf.c +0
-0@@ -415,19 +415,24 @@ void strbuf_vaddf(struct strbuf *sb, const char *fmt, va_list ap)strbuf_setlen (sb, sb->len + len); }
Quoted 8 lines
strbuf.c void strbuf_vaddf(struct strbuf *sb, const char *fmt, va_list ap) · line 421
Quoted 4 lines
strbuf.c +4
-0+int strbuf_expand_step (struct strbuf *sb,const char **formatp) +{ +const char *format = *formatp; +const char *percent =strchrnul (format,'%' );Can format be NULL here? Obviously formatp is never NULL since it is
&s, but we guarded the while loop in the pre-image withwhile (*s)and I am not sure that **formatp is always non-NULL here.
The "*s" in builtin/branch.c::quote_literal_for_format() that you quote dereferences "s", so we'd get a segfault if it was NULL. A NULL (and NUL) check would look like "while (s && *s)". The old code in strbuf.c passes the format to strchrnul(), which can't handle NULL either. So no, format must not be NULL here, and this is not a new requirement.
But now I noticed that builtin/branch.c::quote_literal_for_format() only ever gets called with "" or "remotes/", none of which needs quoting. We could drop this function entirely, and add it back when needed, if ever. But that's out of the scope of this series.
René
Re: [PATCH 2/5] strbuf: factor out strbuf_expand_step()
Quoted 19 lines · René Scharfe
Am 19.06.23 um 18:10 schrieb Taylor Blau:
Quoted 9 lines · René Scharfe
Quoted 8 lines
strbuf.c +0
-0@@ -415,19 +415,24 @@ void strbuf_vaddf(struct strbuf *sb, const char *fmt, va_list ap)strbuf_setlen (sb, sb->len + len); }Quoted 8 lines
strbuf.c void strbuf_vaddf(struct strbuf *sb, const char *fmt, va_list ap) · line 421
Quoted 4 lines
strbuf.c +4
-0+int strbuf_expand_step (struct strbuf *sb,const char **formatp) +{ +const char *format = *formatp; +const char *percent =strchrnul (format,'%' );Can format be NULL here? Obviously formatp is never NULL since it is
&s, but we guarded the while loop in the pre-image withwhile (*s)and I am not sure that **formatp is always non-NULL here.
Quoted 5 lines
The "*s" in builtin/branch.c::quote_literal_for_format() that you quote dereferences "s", so we'd get a segfault if it was NULL. A NULL (and NUL) check would look like "while (s && *s)". The old code in
strbuf.cpasses the format tostrchrnul(), which can't handle NULL either. So no, format must not be NULL here, and this is not a new requirement.
Ah, thanks for catching: I agree with your reasoning.
Quoted 4 lines
But now I noticed that builtin/branch.c::quote_literal_for_format() only ever gets called with "" or "remotes/", none of which needs quoting. We could drop this function entirely, and add it back when needed, if ever. But that's out of the scope of this series.
Yes, agreed.
Thanks,
Taylor
Re: [PATCH 2/5] strbuf: factor out strbuf_expand_step()
In reply to René ScharfeQuoted 10 lines · René Scharfe
Extract the part of
strbuf_expandthat finds the next placeholder into a new function. It allows to build parsers without callback functions and the overhead imposed by them.Signed-off-by René Scharfe <[email protected]>--- builtin/branch.c | 13 ++----------- strbuf.c | 28 ++++++++++++++-------------- strbuf.h | 8 ++++++++ 3 files changed, 24 insertions(+), 25 deletions(-)
I was a little surprised to see the change in branch.c here (as well as the one in strbuf_addftime), since the commit message just says "extract..." and doesn't mention them.
They do serve as examples of how it can be used, so I think it's OK. But it made me wonder: is this all of the sites? Or are these just examples?
-Peff
Re: [PATCH 2/5] strbuf: factor out strbuf_expand_step()
Am 27.06.23 um 10:26 schrieb Jeff King:
Quoted 13 lines · René Scharfe
Quoted 11 lines
Extract the part of
strbuf_expandthat finds the next placeholder into a new function. It allows to build parsers without callback functions and the overhead imposed by them.Signed-off-by René Scharfe <[email protected]>--- builtin/branch.c | 13 ++----------- strbuf.c | 28 ++++++++++++++-------------- strbuf.h | 8 ++++++++ 3 files changed, 24 insertions(+), 25 deletions(-)
Quoted 3 lines
I was a little surprised to see the change in
branch.chere (as well as the one instrbuf_addftime), since the commit message just says "extract..." and doesn't mention them.
Fair point, the other extraction sources should have been mentioned as well somehow.
Quoted 2 lines
They do serve as examples of how it can be used, so I think it's OK. But it made me wonder: is this all of the sites? Or are these just examples?
These are all that I could find.
René
PATCH 3/5 replace strbuf_expand_dict_cb() with strbuf_expand_step()
In reply to René ScharfeAvoid the overhead of setting up a dictionary and passing it via strbuf_expand() to strbuf_expand_dict_cb() by using strbuf_expand_step() in a loop instead. It requires explicit handling of %% and unrecognized placeholders, but is more direct and simpler overall, and expands only on demand.
--- convert.c | 22 ++++++++++------------ ll-merge.c | 32 ++++++++++++++++++-------------- strbuf.c | 16 ---------------- strbuf.h | 14 -------------- 4 files changed, 28 insertions(+), 56 deletions(-)
convert.c +10 -12
@@ -633,23 +633,21 @@ static int filter_buffer_or_fd(int in UNUSED, int out, void *data)*/ struct child_process child_process =CHILD_PROCESS_INIT ;struct filter_params *params = (struct filter_params *)data; +const char *format = params->cmd;int write_err, status;/* apply % substitution to cmd */ struct strbuf cmd =STRBUF_INIT ; -struct strbuf path =STRBUF_INIT ; -struct strbuf_expand_dict_entry dict[] = { - {"f" ,NULL , }, - {NULL ,NULL , }, - }; - -/* quote the path to preserve spaces, etc. */ -sq_quote_buf (&path, params->path); - dict[0 ].value = path.buf; -/* expand all %f with the quoted path */ -strbuf_expand (&cmd, params->cmd, strbuf_expand_dict_cb, &dict); -strbuf_release (&path); +/* expand all %f with the quoted path; quote to preserve space, etc. */ +while (strbuf_expand_step (&cmd, &format)) { +if (skip_prefix (format,"%" , &format)) +strbuf_addch (&cmd,'%' ); +else if (skip_prefix (format,"f" , &format)) +sq_quote_buf (&cmd, params->path); +else +strbuf_addch (&cmd,'%' ); + }strvec_push (&child_process.args, cmd.buf); child_process.use_shell =1 ;
ll-merge.c +18 -14
@@ -192,24 +192,15 @@ static enum ll_merge_result ll_ext_merge(const struct ll_merge_driver *fn,const struct ll_merge_options *opts, int marker_size) { - char temp[4][50]; + char temp[3][50];struct strbuf cmd =STRBUF_INIT ; -struct strbuf_expand_dict_entry dict[6 ]; -struct strbuf path_sq =STRBUF_INIT ; +const char *format = fn->cmdline;struct child_process child =CHILD_PROCESS_INIT ;int status, fd, i;struct stat st;enum ll_merge_result ret;assert (opts); -sq_quote_buf (&path_sq, path); - dict[0 ].placeholder ="O" ; dict[0 ].value = temp[0 ]; - dict[1 ].placeholder ="A" ; dict[1 ].value = temp[1 ]; - dict[2 ].placeholder ="B" ; dict[2 ].value = temp[2 ]; - dict[3 ].placeholder ="L" ; dict[3 ].value = temp[3 ]; - dict[4 ].placeholder ="P" ; dict[4 ].value = path_sq.buf; - dict[5 ].placeholder =NULL ; dict[5 ].value =NULL ; -if (!fn->cmdline)die ("custom merge driver %s lacks command line." , fn->name);
@@ -218,9 +209,23 @@ static enum ll_merge_result ll_ext_merge(const struct ll_merge_driver *fn,create_temp (orig, temp[0 ],sizeof (temp[0 ]));create_temp (src1, temp[1 ],sizeof (temp[1 ]));create_temp (src2, temp[2 ],sizeof (temp[2 ])); -xsnprintf (temp[3 ],sizeof (temp[3 ]),"%d" , marker_size); -strbuf_expand (&cmd, fn->cmdline, strbuf_expand_dict_cb, &dict); +while (strbuf_expand_step (&cmd, &format)) { +if (skip_prefix (format,"%" , &format)) +strbuf_addch (&cmd,'%' ); +else if (skip_prefix (format,"O" , &format)) +strbuf_addstr (&cmd, temp[0 ]); +else if (skip_prefix (format,"A" , &format)) +strbuf_addstr (&cmd, temp[1 ]); +else if (skip_prefix (format,"B" , &format)) +strbuf_addstr (&cmd, temp[2 ]); +else if (skip_prefix (format,"L" , &format)) +strbuf_addf (&cmd,"%d" , marker_size); +else if (skip_prefix (format,"P" , &format)) +sq_quote_buf (&cmd, path); +else +strbuf_addch (&cmd,'%' ); + } child.use_shell =1 ;strvec_push (&child.args, cmd.buf);
@@ -242,7 +247,6 @@ static enum ll_merge_result ll_ext_merge(const struct ll_merge_driver *fn,for (i =0 ; i <3 ; i++)unlink_or_warn (temp[i]);strbuf_release (&cmd); -strbuf_release (&path_sq); ret = (status >0 ) ?LL_MERGE_CONFLICT : status;return ret; }
strbuf.c +0 -16
@@ -468,22 +468,6 @@ size_t strbuf_expand_literal_cb(struct strbuf *sb,return 0 ; } -size_t strbuf_expand_dict_cb (struct strbuf *sb,const char *placeholder, -void *context) -{ -struct strbuf_expand_dict_entry *e = context; -size_t len; - -for (; e->placeholder && (len =strlen (e->placeholder)); e++) { -if (!strncmp (placeholder, e->placeholder, len)) { -if (e->value) -strbuf_addstr (sb, e->value); -return len; - } - } -return 0 ; -} -void strbuf_addbuf_percentquote (struct strbuf *dst,const struct strbuf *src) {size_t i, len = src->len;
strbuf.h +0 -14
@@ -357,20 +357,6 @@ size_t strbuf_expand_literal_cb(struct strbuf *sb,const char *placeholder, void *context); -/** -* Used as callback for `strbuf_expand()`, expects an array of -* struct strbuf_expand_dict_entry as context, i.e. pairs of -* placeholder and replacement string. The array needs to be -* terminated by an entry with placeholder set to NULL. -*/ -struct strbuf_expand_dict_entry { -const char *placeholder; -const char *value; -}; -size_t strbuf_expand_dict_cb (struct strbuf *sb, -const char *placeholder, -void *context); -/** * If the string pointed to by `formatp` contains a percent sign ("%"), * advance it to point to the character following the next one and
--
2.41.0
Re: [PATCH 3/5] replace strbuf_expand_dict_cb() with strbuf_expand_step()
Quoted 5 lines · René Scharfe
Avoid the overhead of setting up a dictionary and passing it via
strbuf_expand()tostrbuf_expand_dict_cb()by usingstrbuf_expand_step()in a loop instead. It requires explicit handling of %% and unrecognized placeholders, but is more direct and simpler overall, and expands only on demand.
Great. I think even replacing the dictionary with regular strbuf_expand() would be an improvement in terms of the on-demand loading. But I am happy to see it go all the way to the iterative version. :)
Your comment above does make me wonder if strbuf_expand_step() should be quietly handling "%%" itself. But I guess strbuf_expand() doesn't, and your branch.c quote-literal example probably would not want that behavior.
-Peff
Re: [PATCH 3/5] replace strbuf_expand_dict_cb() with strbuf_expand_step()
Quoted 4 lines · Jeff King
Your comment above does make me wonder if
strbuf_expand_step()should be quietly handling "%%" itself. But I guessstrbuf_expand()doesn't, and yourbranch.cquote-literal example probably would not want that behavior.
Er, nope, strbuf_expand() does handle "%%" itself. It really feels like we'd want strbuf_expand_step() to do so, too, then. Even if we had two variants (a "raw" one which doesn't handle "%%" so that branch.c could use it, and then another that wrapped it to handle "%%").
-Peff
Re: [PATCH 3/5] replace strbuf_expand_dict_cb() with strbuf_expand_step()
Am 27.06.23 um 10:35 schrieb Jeff King:
Quoted 11 lines · Jeff King
Quoted 5 lines
Your comment above does make me wonder if
strbuf_expand_step()should be quietly handling "%%" itself. But I guessstrbuf_expand()doesn't, and yourbranch.cquote-literal example probably would not want that behavior.Er, nope,
strbuf_expand()does handle "%%" itself. It really feels like we'd wantstrbuf_expand_step()to do so, too, then. Even if we had two variants (a "raw" one which doesn't handle "%%" so thatbranch.ccould use it, and then another that wrapped it to handle "%%").
strbuf_expand() handles %% and unrecognized placeholders.
We could do that, or move the %% handling to strbuf_expand_literal or something else. E.g. initially I had a strbuf_expand_default that handled %% and unrecognized placeholders.
I think it's a good idea to first get used to the loop paradigm by eschewing the sugary automatic handling and having everything spelled out explicitly. It's just one more branch. Then we can come up with a better factoring after a while.
René
PATCH 4/5 replace strbuf_expand() with strbuf_expand_step()
In reply to René ScharfeAvoid the overhead of passing context to a callback function of strbuf_expand() by using strbuf_expand_step() in a loop instead. It requires explicit handling of %% and unrecognized placeholders, but is simpler, more direct and avoids void pointers.
--- builtin/cat-file.c | 35 +++++++-------- builtin/ls-files.c | 109 +++++++++++++++++++-------------------------- builtin/ls-tree.c | 107 +++++++++++++++++--------------------------- daemon.c | 61 ++++++++----------------- pretty.c | 72 ++++++++++++++++++------------ strbuf.c | 20 --------- strbuf.h | 37 ++------------- 7 files changed, 169 insertions(+), 272 deletions(-)
builtin/cat-file.c +17 -18
@@ -309,10 +309,8 @@ static int is_atom(const char *atom, const char *s, int slen) }static void expand_atom (struct strbuf *sb,const char *atom,int len, -void *vdata) +struct expand_data *data) { -struct expand_data *data = vdata; -if (is_atom ("objectname" , atom, len)) {if (!data->mark_query)strbuf_addstr (sb,oid_to_hex (&data->oid));
@@ -346,19 +344,21 @@ static void expand_atom(struct strbuf *sb, const char *atom, int len,die ("unknown format element: %.*s" , len, atom); } -static size_t expand_format (struct strbuf *sb,const char *start,void *data) +static void expand_format (struct strbuf *sb,const char *start, +struct expand_data *data) { -const char *end; - -if (*start !='(' ) -return 0 ; - end =strchr (start +1 ,')' ); -if (!end) -die ("format element '%s' does not end in ')'" , start); - -expand_atom (sb, start +1 , end - start -1 , data); - -return end - start +1 ; +while (strbuf_expand_step (sb, &start)) { +const char *end; + +if (skip_prefix (start,"%" , &start) || *start !='(' ) +strbuf_addch (sb,'%' ); +else if (!(end =strchr (start +1 ,')' ))) +die ("format element '%s' does not end in ')'" , start); +else { +expand_atom (sb, start +1 , end - start -1 , data); + start = end +1 ; + } + } }static void batch_write (struct batch_options *opt,const void *data,int len)
@@ -494,7 +494,7 @@ static void batch_object_write(const char *obj_name,if (!opt->format) {print_default_format (scratch, data); }else { -strbuf_expand (scratch, opt->format, expand_format, data); +expand_format (scratch, opt->format, data);strbuf_addch (scratch,'\n' ); }
@@ -777,9 +777,8 @@ static int batch_objects(struct batch_options *opt)*/ memset (&data,0 ,sizeof (data)); data.mark_query =1 ; -strbuf_expand (&output, +expand_format (&output, opt->format ? opt->format :DEFAULT_FORMAT , - expand_format, &data); data.mark_query =0 ;strbuf_release (&output);
builtin/ls-files.c +46 -63
120 lines not on this page · raw message
builtin/ls-tree.c +41 -66
125 lines not on this page · raw message
daemon.c +19 -42
79 lines not on this page · raw message
pretty.c +43 -29
110 lines not on this page · raw message
strbuf.c +0 -20
@@ -427,26 +427,6 @@ int strbuf_expand_step(struct strbuf *sb, const char **formatp)return 1 ; } -void strbuf_expand (struct strbuf *sb,const char *format,expand_fn_t fn, -void *context) -{ -while (strbuf_expand_step (sb, &format)) { -size_t consumed; - -if (*format =='%' ) { -strbuf_addch (sb,'%' ); - format++; -continue ; - } - - consumed =fn (sb, format, context); -if (consumed) - format += consumed; -else -strbuf_addch (sb,'%' ); - } -} -size_t strbuf_expand_literal_cb (struct strbuf *sb,const char *placeholder, void *context UNUSED)
strbuf.h +3 -34
@@ -318,40 +318,9 @@ const char *strbuf_join_argv(struct strbuf *buf, int argc, const char **argv, char delim);/** -* This function can be used to expand a format string containing -* placeholders. To that end, it parses the string and calls the specified -* function for every percent sign found. -* -* The callback function is given a pointer to the character after the `%` -* and a pointer to the struct strbuf. It is expected to add the expanded -* version of the placeholder to the strbuf, e.g. to add a newline -* character if the letter `n` appears after a `%`. The function returns -* the length of the placeholder recognized and `strbuf_expand()` skips -* over it. -* -* The format `%%` is automatically expanded to a single `%` as a quoting -* mechanism; callers do not need to handle the `%` placeholder themselves, -* and the callback function will not be invoked for this placeholder. -* -* All other characters (non-percent and not skipped ones) are copied -* verbatim to the strbuf. If the callback returned zero, meaning that the -* placeholder is unknown, then the percent sign is copied, too. -* -* In order to facilitate caching and to make it possible to give -* parameters to the callback, `strbuf_expand()` passes a context -* pointer with any kind of data. -*/ -typedef size_t (*expand_fn_t ) (struct strbuf *sb, -const char *placeholder, -void *context); -void strbuf_expand (struct strbuf *sb, -const char *format, -expand_fn_t fn, -void *context); - -/** -* Used as callback for `strbuf_expand` to only expand literals -* (i.e. %n and %xNN). The context argument is ignored. +* Used with `strbuf_expand_step` to expand the literals %n and %x +* followed by two hexadecimal digits. Returns the number of recognized +* characters. The context argument is ignored. */ size_t strbuf_expand_literal_cb(struct strbuf *sb, const char *placeholder,
--
2.41.0
Re: [PATCH 4/5] replace strbuf_expand() with strbuf_expand_step()
Quoted 4 lines · René Scharfe
Avoid the overhead of passing context to a callback function of
strbuf_expand()by usingstrbuf_expand_step()in a loop instead. It requires explicit handling of %% and unrecognized placeholders, but is simpler, more direct and avoids void pointers.
I like this. I don't care that much about the runtime overhead of passing the context around, but if you meant by "overhead" the programmer time and confusion in stuffing everything into context structs, then I agree this is much better. :)
It does still feel like we should be handling "%%" on behalf of the callers.
Quoted 8 lines
builtin/cat-file.c | 35 +++++++-------- builtin/ls-files.c | 109 +++++++++++++++++++-------------------------- builtin/ls-tree.c | 107 +++++++++++++++++--------------------------- daemon.c | 61 ++++++++----------------- pretty.c | 72 ++++++++++++++++++------------ strbuf.c | 20 --------- strbuf.h | 37 ++------------- 7 files changed, 169 insertions(+), 272 deletions(-)
The changes mostly looked OK to me (and the diffstat is certainly pleasing). The old callbacks returned a "consumed" length, and we need each "step" caller to now do "format += consumed" themselves. At first glance I thought there were cases where you didn't, but then I realized that you are relying on skip_prefix() to do that incrementing. Which makes sense and the resulting code looks nice, but it took me a minute to realize what was going on.
Quoted 17 lines
pretty.c +12
-1@@ -1894,7 +1880,26 @@ void userformat_find_requirements(const char *fmt, struct userformat_want *w)return ; fmt = user_format; } -strbuf_expand (&dummy, fmt, userformat_want_item, w); +while (strbuf_expand_step (&dummy, &fmt)) { +if (skip_prefix (fmt,"%" , &fmt)) +continue ; + +if (*fmt =='+' || *fmt =='-' || *fmt ==' ' ) + fmt++; + +switch (*fmt) { +case 'N' : + w->notes =1 ; +break ; +case 'S' :
pretty.c void userformat_find_requirements(const char *fmt, struct userformat_want *w) · line 1904
Quoted 10 lines
pretty.c +8
-0+ w->source =1 ; +break ; +case 'd' : +case 'D' : + w->decorate =1 ; +break ; + } + }strbuf_release (&dummy); }
This one actually doesn't increment the format (so we restart the expansion on "N" or whatever). But neither did the original! It always returned 0:
Quoted 13 lines
pretty.c +0
-13-static size_t userformat_want_item(struct strbuf *sb UNUSED, -const char *placeholder, -void *context) -{ -struct userformat_want *w = context; - -if (*placeholder =='+' || *placeholder =='-' || *placeholder ==' ' ) - placeholder++; - -switch (*placeholder) { -case 'N' : - w->notes =1 ; -break ;
pretty.c static size_t format_commit_item(struct strbuf *sb, /* in UTF-8 */ · line 1886
Quoted 10 lines
pretty.c +0
-10-case 'S' : - w->source =1 ; -break ; -case 'd' : -case 'D' : - w->decorate =1 ; -break ; - } -return 0 ; -}
So probably OK, though a little funny.
It also feels like this whole function would be just as happy using "strchr()", since it throws away the expanded result anyway. But that can be for another time. :)
Quoted 5 lines
pretty.c +0
-1@@ -1912,7 +1917,16 @@ void repo_format_commit_message(struct repository *r,const char *output_enc = pretty_ctx->output_encoding;const char *utf8 ="UTF-8" ; -strbuf_expand (sb, format, format_commit_item, &context);
pretty.c void repo_format_commit_message(struct repository *r, · line 1929
Quoted 10 lines
pretty.c +10
-0+while (strbuf_expand_step (sb, &format)) { +size_t len; + +if (skip_prefix (format,"%" , &format)) +strbuf_addch (sb,'%' ); +else if ((len =format_commit_item (sb, format, &context))) + format += len; +else +strbuf_addch (sb,'%' ); + }
This one doesn't advance the format for a not-understood placeholder. But that's OK, because we know it isn't "%", so starting the search from there again is correct.
pretty.c static size_t format_commit_item(struct strbuf *sb, /* in UTF-8 */ · line 1858
Quoted 9 lines
pretty.c +1
-1@@ -1842,7 +1852,7 @@ static size_t format_commit_item(struct strbuf *sb, /* in UTF-8 */ } orig_len = sb->len; -if (((struct format_commit_context *)context)->flush_type != no_flush) +if ((context)->flush_type != no_flush) consumed =format_and_pad_commit (sb, placeholder, context);else consumed =format_commit_one (sb, placeholder, context);
Since we're no longer casting, the extra parentheses seem redundant now. I.e., this can just be context->flush_type.
-Peff
Re: [PATCH 4/5] replace strbuf_expand() with strbuf_expand_step()
Am 27.06.23 um 10:54 schrieb Jeff King:
Quoted 11 lines · René Scharfe
Quoted 5 lines
Avoid the overhead of passing context to a callback function of
strbuf_expand()by usingstrbuf_expand_step()in a loop instead. It requires explicit handling of %% and unrecognized placeholders, but is simpler, more direct and avoids void pointers.I like this. I don't care that much about the runtime overhead of passing the context around, but if you meant by "overhead" the programmer time and confusion in stuffing everything into context structs, then I agree this is much better. :)
Indeed, I meant the burden of being forced to define a struct and filling in all necessary context. Bureaucratic overhead.
Quoted 2 lines
It does still feel like we should be handling "%%" on behalf of the callers.
I feel the same, but restrained myself from doing that, so that we can see all the pieces for now. It allows us to recombine them in better ways than before.
Quoted 9 lines
Quoted 8 lines
builtin/cat-file.c | 35 +++++++-------- builtin/ls-files.c | 109 +++++++++++++++++++-------------------------- builtin/ls-tree.c | 107 +++++++++++++++++--------------------------- daemon.c | 61 ++++++++----------------- pretty.c | 72 ++++++++++++++++++------------ strbuf.c | 20 --------- strbuf.h | 37 ++------------- 7 files changed, 169 insertions(+), 272 deletions(-)
Quoted 7 lines
The changes mostly looked OK to me (and the diffstat is certainly pleasing). The old callbacks returned a "consumed" length, and we need each "step" caller to now do "format += consumed" themselves. At first glance I thought there were cases where you didn't, but then I realized that you are relying on
skip_prefix()to do that incrementing. Which makes sense and the resulting code looks nice, but it took me a minute to realize what was going on.
*nod* The "returns consumed length" style is still used by strbuf_expand_literal, though, so we have a bit of a mix. Which works, but a uniform convention might be better.
Quoted 58 lines
Quoted 17 lines
pretty.c +12
-1@@ -1894,7 +1880,26 @@ void userformat_find_requirements(const char *fmt, struct userformat_want *w)return ; fmt = user_format; } -strbuf_expand (&dummy, fmt, userformat_want_item, w); +while (strbuf_expand_step (&dummy, &fmt)) { +if (skip_prefix (fmt,"%" , &fmt)) +continue ; + +if (*fmt =='+' || *fmt =='-' || *fmt ==' ' ) + fmt++; + +switch (*fmt) { +case 'N' : + w->notes =1 ; +break ; +case 'S' :pretty.c void userformat_find_requirements(const char *fmt, struct userformat_want *w) · line 1904
Quoted 10 lines
pretty.c +8
-0+ w->source =1 ; +break ; +case 'd' : +case 'D' : + w->decorate =1 ; +break ; + } + }strbuf_release (&dummy); }This one actually doesn't increment the format (so we restart the expansion on "N" or whatever). But neither did the original! It always returned 0:
Quoted 13 lines
pretty.c +0
-13-static size_t userformat_want_item(struct strbuf *sb UNUSED, -const char *placeholder, -void *context) -{ -struct userformat_want *w = context; - -if (*placeholder =='+' || *placeholder =='-' || *placeholder ==' ' ) - placeholder++; - -switch (*placeholder) { -case 'N' : - w->notes =1 ; -break ;pretty.c static size_t format_commit_item(struct strbuf *sb, /* in UTF-8 */ · line 1886
Quoted 10 lines
pretty.c +0
-10-case 'S' : - w->source =1 ; -break ; -case 'd' : -case 'D' : - w->decorate =1 ; -break ; - } -return 0 ; -}So probably OK, though a little funny.
Quoted 3 lines
It also feels like this whole function would be just as happy using "
strchr()", since it throws away the expanded result anyway. But that can be for another time. :)
Good idea! And the conversion to a loop brings us halfway there.
Quoted 5 lines
Quoted 5 lines
pretty.c +0
-0@@ -1912,7 +1917,16 @@ void repo_format_commit_message(struct repository *r,const char *output_enc = pretty_ctx->output_encoding;const char *utf8 ="UTF-8" ;
Quoted 15 lines
pretty.c void repo_format_commit_message(struct repository *r, · line 1929
Quoted 11 lines
pretty.c +10
-1-strbuf_expand (sb, format, format_commit_item, &context); +while (strbuf_expand_step (sb, &format)) { +size_t len; + +if (skip_prefix (format,"%" , &format)) +strbuf_addch (sb,'%' ); +else if ((len =format_commit_item (sb, format, &context))) + format += len; +else +strbuf_addch (sb,'%' ); + }This one doesn't advance the format for a not-understood placeholder. But that's OK, because we know it isn't "%", so starting the search from there again is correct.
Right. This is copied from strbuf_expand.
Quoted 4 lines
Quoted 4 lines
(quoted diff) +0
-0@@ -1842,7 +1852,7 @@ static size_t format_commit_item(struct strbuf *sb, /* in UTF-8 */ }
Quoted 9 lines
pretty.c static size_t format_commit_item(struct strbuf *sb, /* in UTF-8 */ · line 1858
Quoted 6 lines
pretty.c +1
-1orig_len = sb->len; -if (((struct format_commit_context *)context)->flush_type != no_flush) +if ((context)->flush_type != no_flush) consumed =format_and_pad_commit (sb, placeholder, context);else consumed =format_commit_one (sb, placeholder, context);Since we're no longer casting, the extra parentheses seem redundant now. I.e., this can just be
context->flush_type.
Indeed.
René
Re: [PATCH 4/5] replace strbuf_expand() with strbuf_expand_step()
Quoted 6 lines · René Scharfe
Quoted 2 lines
It does still feel like we should be handling "%%" on behalf of the callers.
I feel the same, but restrained myself from doing that, so that we can see all the pieces for now. It allows us to recombine them in better ways than before.
Yeah, since you did the work to handle "%%" in each caller, I'm OK with proceeding and letting a later refactor shrink it back down if we choose.
-Peff
PATCH 5/5 strbuf: simplify strbuf_expand_literal_cb()
In reply to René ScharfeNow that strbuf_expand_literal_cb() is no longer used as a callback, drop its "_cb" name suffix and unused context parameter.
--- builtin/ls-files.c | 2 +- builtin/ls-tree.c | 2 +- pretty.c | 4 ++-- strbuf.c | 4 +--- strbuf.h | 6 ++---- 5 files changed, 7 insertions(+), 11 deletions(-)
builtin/ls-files.c +1 -1
@@ -274,7 +274,7 @@ static void show_ce_fmt(struct repository *repo, const struct cache_entry *ce,if (skip_prefix (format,"%" , &format))strbuf_addch (&sb,'%' ); -else if ((len =strbuf_expand_literal_cb (&sb, format,NULL ))) +else if ((len =strbuf_expand_literal (&sb, format))) format += len;else if (*format !='(' ) die(_("bad ls-files format: element '%s' "
builtin/ls-tree.c +1 -1
@@ -108,7 +108,7 @@ static int show_tree_fmt(const struct object_id *oid, struct strbuf *base,if (skip_prefix (format,"%" , &format))strbuf_addch (&sb,'%' ); -else if ((len =strbuf_expand_literal_cb (&sb, format,NULL ))) +else if ((len =strbuf_expand_literal (&sb, format))) format += len;else if (*format !='(' ) die(_("bad ls-tree format: element '%s' "
pretty.c +2 -2
@@ -1262,7 +1262,7 @@ static struct strbuf *expand_separator(struct strbuf *sb,if (skip_prefix (format,"%" , &format))strbuf_addch (sb,'%' ); -else if ((len =strbuf_expand_literal_cb (sb, format,NULL ))) +else if ((len =strbuf_expand_literal (sb, format))) format += len;else strbuf_addch (sb,'%' );
@@ -1395,7 +1395,7 @@ static size_t format_commit_one(struct strbuf *sb, /* in UTF-8 */char **slot;/* these are independent of the commit */ - res =strbuf_expand_literal_cb (sb, placeholder,NULL ); + res =strbuf_expand_literal (sb, placeholder);if (res)return res;
strbuf.c +1 -3
@@ -427,9 +427,7 @@ int strbuf_expand_step(struct strbuf *sb, const char **formatp)return 1 ; } -size_t strbuf_expand_literal_cb (struct strbuf *sb, -const char *placeholder, - void *context UNUSED) +size_t strbuf_expand_literal (struct strbuf *sb,const char *placeholder) {int ch;
strbuf.h +2 -4
@@ -320,11 +320,9 @@ const char *strbuf_join_argv(struct strbuf *buf, int argc,/** * Used with `strbuf_expand_step` to expand the literals %n and %x * followed by two hexadecimal digits. Returns the number of recognized -* characters. The context argument is ignored. +* characters. */ -size_t strbuf_expand_literal_cb (struct strbuf *sb, -const char *placeholder, -void *context); +size_t strbuf_expand_literal (struct strbuf *sb,const char *placeholder);/** * If the string pointed to by `formatp` contains a percent sign ("%"),
--
2.41.0
Re: [PATCH 5/5] strbuf: simplify strbuf_expand_literal_cb()
Quoted 2 lines · René Scharfe
Now that
strbuf_expand_literal_cb()is no longer used as a callback, drop its "_cb" name suffix and unused context parameter.
Makes sense.
Since most callers just call "format += len", it kind of feels like the appropriate interface might be more like:
strbuf_expand_literal(&sb, &format);
to auto-advance the format. But I guess that gets weird with this caller:
pretty.c static size_t format_commit_one(struct strbuf *sb, /* in UTF-8 */ · line 1400
Quoted 8 lines
pretty.c +1
-1@@ -1395,7 +1395,7 @@ static size_t format_commit_one(struct strbuf *sb, /* in UTF-8 */char **slot;/* these are independent of the commit */ - res =strbuf_expand_literal_cb (sb, placeholder,NULL ); + res =strbuf_expand_literal (sb, placeholder);if (res)return res;
which is still in the "return the length" mentality (OTOH, if it advanced the local copy of the placeholder pointer nobody would mind).
I dunno. It is a little thing, and I am OK with it either way (I would not even think of changing it if you were not already touching the function).
-Peff
Re: [PATCH 5/5] strbuf: simplify strbuf_expand_literal_cb()
Am 27.06.23 um 10:57 schrieb Jeff King:
Quoted 18 lines · René Scharfe
Quoted 3 lines
Now that
strbuf_expand_literal_cb()is no longer used as a callback, drop its "_cb" name suffix and unused context parameter.Makes sense.
Since most callers just call "format += len", it kind of feels like the appropriate interface might be more like:
strbuf_expand_literal(&sb, &format);to auto-advance the format. But I guess that gets weird with this caller:
Quoted 3 lines
pretty.c +0
-0@@ -1395,7 +1395,7 @@ static size_t format_commit_one(struct strbuf *sb, /* in UTF-8 */char **slot;
Quoted 8 lines
pretty.c static size_t format_commit_one(struct strbuf *sb, /* in UTF-8 */ · line 1400
Quoted 5 lines
pretty.c +1
-1/* these are independent of the commit */ - res =strbuf_expand_literal_cb (sb, placeholder,NULL ); + res =strbuf_expand_literal (sb, placeholder);if (res)return res;which is still in the "return the length" mentality (OTOH, if it advanced the local copy of the placeholder pointer nobody would mind).
Yes, I only grabbed the two low-hanging fruits here.
A format-advancing version would also look a bit weird in an if/else cascade:
else if (strbuf_expand_literal(&sb, &format)) ; /* nothing */ else ...
Quoted 3 lines
I dunno. It is a little thing, and I am OK with it either way (I would not even think of changing it if you were not already touching the function).
Unsure. Should I overcome my horror vacui and let the /* nothing */ in?
René
Re: [PATCH 5/5] strbuf: simplify strbuf_expand_literal_cb()
Quoted 7 lines · René Scharfe
A format-advancing version would also look a bit weird in an if/else cascade:
else if (strbuf_expand_literal(&sb, &format)) ; /* nothing */ else ...
Quoted 5 lines
Quoted 3 lines
I dunno. It is a little thing, and I am OK with it either way (I would not even think of changing it if you were not already touching the function).
Unsure. Should I overcome my horror vacui and let the /* nothing */ in?
Heh. It is a little funny to have an empty block. But at the same time, it aligns the conditional with all of the skip_prefix() calls, which are advancing "format" as a side effect of matching.
So I could go either way (and we can always change it on top).
I think based on your responses that there's nothing that would require a re-roll. The only thing left from my review is the extra parentheses in format_commit_item, which could possibly be fixed up while applying.
-Peff