From 005c9b6a473fedd8c861d85d93f4bc2168dddd2c Mon Sep 17 00:00:00 2001 From: Explorer09 Date: Tue, 21 Jan 2025 04:46:55 +0800 Subject: [PATCH] Introduce RichString_append{,n}FormatAscii functions --- RichString.c | 43 +++++++++++++++++++++++++++++++++++++++++++ RichString.h | 6 ++++++ 2 files changed, 49 insertions(+) diff --git a/RichString.c b/RichString.c index f79e6efe3..1189ff146 100644 --- a/RichString.c +++ b/RichString.c @@ -12,6 +12,7 @@ in the source distribution for its full text. #include #include #include // IWYU pragma: keep +#include #include #include #include @@ -297,3 +298,45 @@ size_t RichString_appendnAscii(RichString* this, int attrs, const char* data, si size_t RichString_writeAscii(RichString* this, int attrs, const char* data) { return RichString_writeFromAscii(this, attrs, data, 0, strlen(data)); } + +ATTR_FORMAT(printf, 5, 0) ATTR_NONNULL_N(1, 3, 5) +static size_t RichString_appendvnFormatAscii(RichString* this, int attrs, char* buf, size_t len, const char* fmt, va_list vl) { + // The temporary "buf" does not need to be NUL-terminated. + int ret = vsnprintf(buf, len, fmt, vl); + if (ret < 0 || (unsigned int)ret > len) { + fail(); + } + + return RichString_appendnAscii(this, attrs, buf, (unsigned int)ret); +} + +size_t RichString_appendnFormatAscii(RichString* this, int attrs, char* buf, size_t len, const char* fmt, ...) { + va_list vl; + va_start(vl, fmt); + size_t ret = RichString_appendvnFormatAscii(this, attrs, buf, len, fmt, vl); + va_end(vl); + + return ret; +} + +ATTR_FORMAT(printf, 3, 0) ATTR_NONNULL_N(1, 3) +static size_t RichString_appendvFormatAscii(RichString* this, int attrs, const char* fmt, va_list vl) { + char* buf; + int ret = vasprintf(&buf, fmt, vl); + if (ret < 0 || !buf) { + fail(); + } + + size_t len = RichString_appendnAscii(this, attrs, buf, (unsigned int)ret); + free(buf); + return len; +} + +size_t RichString_appendFormatAscii(RichString* this, int attrs, const char* fmt, ...) { + va_list vl; + va_start(vl, fmt); + size_t len = RichString_appendvFormatAscii(this, attrs, fmt, vl); + va_end(vl); + + return len; +} diff --git a/RichString.h b/RichString.h index 78f8005c8..71eee8435 100644 --- a/RichString.h +++ b/RichString.h @@ -79,4 +79,10 @@ size_t RichString_appendnAscii(RichString* this, int attrs, const char* data, si size_t RichString_writeAscii(RichString* this, int attrs, const char* data); +ATTR_FORMAT(printf, 5, 6) ATTR_NONNULL_N(1, 3, 5) +size_t RichString_appendnFormatAscii(RichString* this, int attrs, char* buf, size_t len, const char* fmt, ...); + +ATTR_FORMAT(printf, 3, 4) ATTR_NONNULL_N(1, 3) +size_t RichString_appendFormatAscii(RichString* this, int attrs, const char* fmt, ...); + #endif