Skip to content

Commit ca1395c

Browse files
committed
strbuf: add compound literal test balloon
C99's compound literals create an unnamed object whose value is given by an initializer list. This allows us to simplify code where we cannot use a designated initalizer because the values of some members of the object need to be calculated first. For example this code from builtin/rebase.c struct strbuf branch_reflog = STRBUF_INIT, head_reflog = STRBUF_INIT; struct reset_head_opts ropts = { 0 }; int ret; strbuf_addf(&branch_reflog, "%s (finish): %s onto %s", opts->reflog_action, opts->head_name, oid_to_hex(&opts->onto->object.oid)); strbuf_addf(&head_reflog, "%s (finish): returning to %s", opts->reflog_action, opts->head_name); ropts.branch = opts->head_name; ropts.flags = RESET_HEAD_REFS_ONLY; ropts.branch_msg = branch_reflog.buf; ropts.head_msg = head_reflog.buf; ret = reset_head(the_repository, &ropts); can be be simplified to struct strbuf branch_reflog = STRBUF_INIT, head_reflog = STRBUF_INIT; int ret; strbuf_addf(&branch_reflog, "%s (finish): %s onto %s", opts->reflog_action, opts->head_name, oid_to_hex(&opts->onto->object.oid)); strbuf_addf(&head_reflog, "%s (finish): returning to %s", opts->reflog_action, opts->head_name); ret = reset_head(the_repository, (struct reset_head_opts) { .branch = opts->head_name, .flags = RESET_HEAD_REFS_ONLY, .branch_msg = branch_reflog.buf, .head_msg = head_reflog.buf, }); The result is more readable as one can see the value of each member of the object being passed to the function at the call site rather than building the object piecemeal in the preceding lines. A common pattern in our code base is to define a struct together with an initializer macro to initialize automatic variables and an initializer function to initialize dynamically allocated instances of the struct. Typically the initializer function for "struct foo" looks like void foo_init(struct foo *f) { struct foo blank = FOO_INIT; memcpy(f, &blank, sizeof(*f)); } which enables us to reuse the initializer macro FOO_INIT. Using compound literals we can simplify this to void foo_init(struct foo *f) { *f = (struct foo) FOO_INIT; } Let's add a test balloon to check for compiler support by changing strbuf_init() to use a compound literal. Signed-off-by: Phillip Wood <[email protected]>
1 parent a30f80f commit ca1395c

File tree

1 file changed

+1
-2
lines changed

1 file changed

+1
-2
lines changed

strbuf.c

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,8 +68,7 @@ char strbuf_slopbuf[1];
6868

6969
void strbuf_init(struct strbuf *sb, size_t hint)
7070
{
71-
struct strbuf blank = STRBUF_INIT;
72-
memcpy(sb, &blank, sizeof(*sb));
71+
*sb = (struct strbuf) STRBUF_INIT;
7372
if (hint)
7473
strbuf_grow(sb, hint);
7574
}

0 commit comments

Comments
 (0)