diff options
| author | Sean Kurtz <seankurtz75@gmail.com> | 2026-11-28 14:16:41 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-11-28 14:16:41 -0600 |
| commit | 95d31d2d7d5fd7de81d6d5e2caedcdc369ca0fcf (patch) | |
| tree | 4959b8d43268945543be4061b8fccd95d04592b1 /src/printf.c | |
| parent | 625908ab56c7c554506d61c83c7001bca19a05f6 (diff) | |
| parent | 6fe2aff8d6611bf45704ba86120efa23950bfa80 (diff) | |
| download | zash-95d31d2d7d5fd7de81d6d5e2caedcdc369ca0fcf.tar.gz | |
Merge pull request #46 from skurtz97/fix/review-2026-11-28
Fixes from the 2026-11-28 code review
Diffstat (limited to 'src/printf.c')
| -rw-r--r-- | src/printf.c | 24 |
1 files changed, 20 insertions, 4 deletions
diff --git a/src/printf.c b/src/printf.c index 3e33c53..fabc0b3 100644 --- a/src/printf.c +++ b/src/printf.c @@ -150,12 +150,23 @@ static double arg_double(printf_state *pf) { * @param f Position in the format. * @param spec Specification being built. * @param n Receives the new length of `spec`. + * @param dot Length of `spec` before the '.' that starts this precision, + * or 0 when this is the width. * @return Position in the format after the number. */ static const char *copy_number(printf_state *pf, const char *f, char *spec, - size_t *n) { + size_t *n, size_t dot) { if (*f == '*') { - *n += (size_t)snprintf(spec + *n, 16, "%d", (int)arg_int(pf)); + intmax_t v = arg_int(pf); + /* + * C99: a negative precision is as if the precision were omitted, + * so drop the '.' as well; a negative width is a '-' flag, which + * snprintf() reads from the "%*d" this writes. + */ + if (dot && v < 0) + *n = dot; + else + *n += (size_t)snprintf(spec + *n, 24, "%jd", v); return f + 1; } int digits = 0; @@ -184,10 +195,11 @@ static const char *convert(printf_state *pf, const char *f) { spec[n++] = *f; f++; } - f = copy_number(pf, f, spec, &n); + f = copy_number(pf, f, spec, &n, 0); if (*f == '.') { + size_t dot = n; spec[n++] = '.'; - f = copy_number(pf, f + 1, spec, &n); + f = copy_number(pf, f + 1, spec, &n, dot); } switch (*f) { case 'd': @@ -228,6 +240,10 @@ static const char *convert(printf_state *pf, const char *f) { } case 's': { const char *s = next_arg(pf); + if (n == 1) { /* a bare "%s": there is nothing to pad or truncate */ + out_puts(&out1, s ? s : ""); + break; + } spec[n++] = 's'; spec[n] = '\0'; out_printf(&out1, spec, s ? s : ""); |
