diff options
author | Thomas Weißschuh <thomas.weissschuh@linutronix.de> | 2025-04-11 11:00:49 +0200 |
---|---|---|
committer | Thomas Weißschuh <linux@weissschuh.net> | 2025-04-22 10:59:02 +0200 |
commit | f7b3eeffd402c5eec32be9c3bfdeb3ec03e87cf3 (patch) | |
tree | c419c4d1e35e655933405132405f2e878db28b9d | |
parent | bae3cd708e8adef27ee7657cd877d9ba9aa4f2ae (diff) |
tools/nolibc: allow different write callbacks in printf
Decouple the formatting logic from the writing logic to later enable
writing straight to a buffer in sprintf().
Signed-off-by: Thomas Weißschuh <thomas.weissschuh@linutronix.de>
Acked-by: Willy Tarreau <w@1wt.eu>
-rw-r--r-- | tools/include/nolibc/stdio.h | 21 |
1 files changed, 17 insertions, 4 deletions
diff --git a/tools/include/nolibc/stdio.h b/tools/include/nolibc/stdio.h index 262d0da4da90..5c893b4903a3 100644 --- a/tools/include/nolibc/stdio.h +++ b/tools/include/nolibc/stdio.h @@ -208,13 +208,15 @@ char *fgets(char *s, int size, FILE *stream) } -/* minimal vfprintf(). It supports the following formats: +/* minimal printf(). It supports the following formats: * - %[l*]{d,u,c,x,p} * - %s * - unknown modifiers are ignored. */ -static __attribute__((unused, format(printf, 2, 0))) -int vfprintf(FILE *stream, const char *fmt, va_list args) +typedef int (*__nolibc_printf_cb)(intptr_t state, const char *buf, size_t size); + +static __attribute__((unused, format(printf, 3, 0))) +int __nolibc_printf(__nolibc_printf_cb cb, intptr_t state, const char *fmt, va_list args) { char escape, lpref, c; unsigned long long v; @@ -304,7 +306,7 @@ int vfprintf(FILE *stream, const char *fmt, va_list args) outstr = fmt; len = ofs - 1; flush_str: - if (_fwrite(outstr, len, stream) != 0) + if (cb(state, outstr, len) != 0) break; written += len; @@ -321,6 +323,17 @@ int vfprintf(FILE *stream, const char *fmt, va_list args) return written; } +static int __nolibc_fprintf_cb(intptr_t state, const char *buf, size_t size) +{ + return _fwrite(buf, size, (FILE *)state); +} + +static __attribute__((unused, format(printf, 2, 0))) +int vfprintf(FILE *stream, const char *fmt, va_list args) +{ + return __nolibc_printf(__nolibc_fprintf_cb, (intptr_t)stream, fmt, args); +} + static __attribute__((unused, format(printf, 1, 0))) int vprintf(const char *fmt, va_list args) { |