*.c *_init(): define in terms of corresponding *_INIT macro

Change the common patter in the codebase of duplicating the initialization logic between an *_INIT macro and a corresponding *_init() function to use the macro as the canonical source of truth. Now we no longer need to keep the function up-to-date with the macro version. This implements a suggestion by Jeff King who found that under -O2 [1] modern compilers will init new version in place without the extra copy[1]. The performance of a single *_init() won't matter in most cases, but even if it does we're going to be producing efficient machine code to perform these operations. 1. https://lore.kernel.org/git/YNyrDxUO1PlGJvCn@coredump.intra.peff.net/ Signed-off-by: Ævar Arnfjörð Bjarmason <avarab@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Ævar Arnfjörð Bjarmason committed Jul 1, 2021 at 12:51 UTC 5726a6b4012cd41701927a6637b9f2070e7760ee
6 files changed +12 -15
credential.c
+2 -2
@@ -10,8 +10,8 @@
10
11 void credential_init(struct credential *c)
12 {
13 - memset(c, 0, sizeof(*c));
14 - c->helpers.strdup_strings = 1;
13 + struct credential blank = CREDENTIAL_INIT;
14 + memcpy(c, &blank, sizeof(*c));
15 }
16
17 void credential_clear(struct credential *c)
json-writer.c
+2 -4
@@ -3,10 +3,8 @@
3
4 void jw_init(struct json_writer *jw)
5 {
6 - strbuf_init(&jw->json, 0);
7 - strbuf_init(&jw->open_stack, 0);
8 - jw->need_comma = 0;
9 - jw->pretty = 0;
6 + struct json_writer blank = JSON_WRITER_INIT;
7 + memcpy(jw, &blank, sizeof(*jw));;
8 }
9
10 void jw_release(struct json_writer *jw)
run-command.c
+2 -3
@@ -11,9 +11,8 @@
11
12 void child_process_init(struct child_process *child)
13 {
14 - memset(child, 0, sizeof(*child));
15 - strvec_init(&child->args);
16 - strvec_init(&child->env_array);
14 + struct child_process blank = CHILD_PROCESS_INIT;
15 + memcpy(child, &blank, sizeof(*child));
16 }
17
18 void child_process_clear(struct child_process *child)
strbuf.c
+2 -2
@@ -52,8 +52,8 @@ char strbuf_slopbuf[1];
52
53 void strbuf_init(struct strbuf *sb, size_t hint)
54 {
55 - sb->alloc = sb->len = 0;
56 - sb->buf = strbuf_slopbuf;
55 + struct strbuf blank = STRBUF_INIT;
56 + memcpy(sb, &blank, sizeof(*sb));
57 if (hint)
58 strbuf_grow(sb, hint);
59 }
strmap.c
+2 -1
@@ -25,7 +25,8 @@ static struct strmap_entry *find_strmap_entry(struct strmap *map,
25
26 void strmap_init(struct strmap *map)
27 {
28 - strmap_init_with_options(map, NULL, 1);
28 + struct strmap blank = STRMAP_INIT;
29 + memcpy(map, &blank, sizeof(*map));
30 }
31
32 void strmap_init_with_options(struct strmap *map,
strvec.c
+2 -3
@@ -6,9 +6,8 @@ const char *empty_strvec[] = { NULL };
6
7 void strvec_init(struct strvec *array)
8 {
9 - array->v = empty_strvec;
10 - array->nr = 0;
11 - array->alloc = 0;
9 + struct strvec blank = STRVEC_INIT;
10 + memcpy(array, &blank, sizeof(*array));
11 }
12
13 static void strvec_push_nodup(struct strvec *array, const char *value)