scc

simple c99 compiler
git clone git://git.simple-cc.org/scc
Log | Files | Refs | Submodules | README | LICENSE

commit 0e6a91f0ad480a0a2e1745679c3cf712f19b4719
parent ac419b4e9017c49736a13de9689992652c133b16
Author: Roberto E. Vargas Caballero <k0ga@shike2.com>
Date:   Mon,  7 Nov 2022 13:04:56 +0100

libc/stdio: Simplify string output in vfprintf()

It is not needed to calculate the lenght of a string because
we already check it while we print it and it is cross checked
against the precision. We can use SIZE_MAX instead of -1 because
it works as a positive number, removing several of the problems
that the code had.

Diffstat:
Msrc/libc/stdio/vfprintf.c | 15+++++----------
1 file changed, 5 insertions(+), 10 deletions(-)

diff --git a/src/libc/stdio/vfprintf.c b/src/libc/stdio/vfprintf.c @@ -25,7 +25,7 @@ enum { struct conv { int sign; - int prec; + size_t prec; char *digs; int base; }; @@ -75,7 +75,7 @@ numtostr(uintmax_t val, int flags, struct conv *conv, char *buf) int base = conv->base, prec = conv->prec; uintmax_t oval = val; - if (prec == -1) + if (prec == SIZE_MAX) prec = 1; for (*buf = '\0'; val > 0; val /= base) @@ -158,8 +158,6 @@ strout(char *s, size_t len, int width, int fill, FILE *restrict fp) left = 1; width = -width; } - if (len == (size_t) -1) - len = SIZE_MAX; adjust = len < width ? width - len : 0; if (left) @@ -219,7 +217,7 @@ vfprintf(FILE *restrict fp, const char *restrict fmt, va_list va) fill = ' '; left = flags = width = 0; - conv.prec = -1; + conv.prec = SIZE_MAX; conv.base = 10; conv.sign = '\0'; conv.digs = "0123456789ABCDEFX"; @@ -324,7 +322,7 @@ flags: conv.base = 8; flags |= UNSIGNED; numeric: - if (conv.prec != -1) { + if (conv.prec != SIZE_MAX) { if (conv.prec > MAXPREC) conv.prec = MAXPREC; fill = ' '; @@ -346,15 +344,12 @@ flags: /* TODO */ break; case 's': + len = conv.prec; if (flags & LONG) { ws = va_arg(va2, wchar_t *); - if ((len = wcslen(ws)) > conv.prec) - len = conv.prec; goto wstrout; } else { s = va_arg(va2, char *); - if ((len = strlen(s)) > conv.prec) - len = conv.prec; goto strout; } wstrout: