@matheusbsbs / matheus-bagliano / commits / 4acfd1b799
Fork 0

Change semantics of interpolate to work like snprintf.

Also fix many off-by-ones and a useless memset. Signed-off-by: Pierre Habouzit <madcoder@debian.org> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Pierre Habouzit committed Sep 10, 2007 at 12:35 UTC 4acfd1b799acf43642a28a22cc794266c25129ef
2 files changed +13 -16
commit.c
+4 -5
@@ -923,15 +923,14 @@ long format_commit_message(const struct commit *commit, const void *format,
923
924 do {
925 char *buf = *buf_p;
926 - unsigned long space = *space_p;
926 + unsigned long len;
927
928 - space = interpolate(buf, space, format,
928 + len = interpolate(buf, *space_p, format,
929 table, ARRAY_SIZE(table));
930 - if (!space)
930 + if (len < *space_p)
931 break;
932 - buf = xrealloc(buf, space);
932 + ALLOC_GROW(buf, len + 1, *space_p);
933 *buf_p = buf;
934 - *space_p = space;
934 } while (1);
935 interp_clear_table(table, ARRAY_SIZE(table));
936
interpolate.c
+9 -11
@@ -44,9 +44,8 @@ void interp_clear_table(struct interp *table, int ninterps)
44 * { "%%", "%"},
45 * }
46 *
47 - * Returns 0 on a successful substitution pass that fits in result,
48 - * Returns a number of bytes needed to hold the full substituted
49 - * string otherwise.
47 + * Returns the length of the substituted string (not including the final \0).
48 + * Like with snprintf, if the result is >= reslen, then it overflowed.
49 */
50
51 unsigned long interpolate(char *result, unsigned long reslen,
@@ -61,8 +60,6 @@ unsigned long interpolate(char *result, unsigned long reslen,
60 int i;
61 char c;
62
64 - memset(result, 0, reslen);
65 -
63 while ((c = *src)) {
64 if (c == '%') {
65 /* Try to match an interpolation string. */
@@ -78,9 +75,9 @@ unsigned long interpolate(char *result, unsigned long reslen,
75 value = interps[i].value;
76 valuelen = strlen(value);
77
81 - if (newlen + valuelen + 1 < reslen) {
78 + if (newlen + valuelen < reslen) {
79 /* Substitute. */
83 - strncpy(dest, value, valuelen);
80 + memcpy(dest, value, valuelen);
81 dest += valuelen;
82 }
83 newlen += valuelen;
@@ -95,8 +92,9 @@ unsigned long interpolate(char *result, unsigned long reslen,
92 newlen++;
93 }
94
98 - if (newlen + 1 < reslen)
99 - return 0;
100 - else
101 - return newlen + 2;
95 + /* XXX: the previous loop always keep room for the ending NUL,
96 + we just need to check if there was room for a NUL in the first place */
97 + if (reslen > 0)
98 + *dest = '\0';
99 + return newlen;
100 }