Skip to content

Commit

Permalink
Introduce RichString_append{,n}FormatAscii functions
Browse files Browse the repository at this point in the history
  • Loading branch information
Explorer09 committed Jan 23, 2025
1 parent 1b8f1ab commit 005c9b6
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
43 changes: 43 additions & 0 deletions RichString.c
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ in the source distribution for its full text.
#include <assert.h>
#include <ctype.h>
#include <limits.h> // IWYU pragma: keep
#include <stdarg.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
Expand Down Expand Up @@ -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;
}
6 changes: 6 additions & 0 deletions RichString.h
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 005c9b6

Please sign in to comment.