X-Git-Url: https://git.tokkee.org/?a=blobdiff_plain;f=interpolate.c;h=7f03bd99c5b66afa6cc7fa11a2430301a3042656;hb=2b6f0b0a78a713be51149f27c2c1172fe4afc9cd;hp=2f727cd05b0d071d9aa750b90fe3c16c12ccbe5e;hpb=55246aac6717e86c14f31391ac903ed810d1a9a0;p=git.git diff --git a/interpolate.c b/interpolate.c index 2f727cd05..7f03bd99c 100644 --- a/interpolate.c +++ b/interpolate.c @@ -11,8 +11,7 @@ void interp_set_entry(struct interp *table, int slot, const char *value) char *oldval = table[slot].value; char *newval = NULL; - if (oldval) - free(oldval); + free(oldval); if (value) newval = xstrdup(value); @@ -44,9 +43,8 @@ void interp_clear_table(struct interp *table, int ninterps) * { "%%", "%"}, * } * - * Returns 0 on a successful substitution pass that fits in result, - * Returns a number of bytes needed to hold the full substituted - * string otherwise. + * Returns the length of the substituted string (not including the final \0). + * Like with snprintf, if the result is >= reslen, then it overflowed. */ unsigned long interpolate(char *result, unsigned long reslen, @@ -61,8 +59,6 @@ unsigned long interpolate(char *result, unsigned long reslen, int i; char c; - memset(result, 0, reslen); - while ((c = *src)) { if (c == '%') { /* Try to match an interpolation string. */ @@ -82,9 +78,9 @@ unsigned long interpolate(char *result, unsigned long reslen, } valuelen = strlen(value); - if (newlen + valuelen + 1 < reslen) { + if (newlen + valuelen < reslen) { /* Substitute. */ - strncpy(dest, value, valuelen); + memcpy(dest, value, valuelen); dest += valuelen; } newlen += valuelen; @@ -99,8 +95,9 @@ unsigned long interpolate(char *result, unsigned long reslen, newlen++; } - if (newlen + 1 < reslen) - return 0; - else - return newlen + 2; + /* XXX: the previous loop always keep room for the ending NUL, + we just need to check if there was room for a NUL in the first place */ + if (reslen > 0) + *dest = '\0'; + return newlen; }