Add string_format and vstring_format

This commit is contained in:
apio 2022-11-30 12:36:21 +01:00
parent 1ed51d11cb
commit 552186ad51
2 changed files with 42 additions and 1 deletions

View File

@ -468,3 +468,42 @@ Result<usize> cstyle_format(const char* format, callback_t callback, void* arg,
return state.count;
}
struct StringFormatInfo
{
char* buffer;
size_t remaining;
};
Result<usize> vstring_format(char* buf, size_t max, const char* format, va_list ap)
{
StringFormatInfo info = {.buffer = buf, .remaining = max - 1};
usize result = TRY(cstyle_format(
format,
[](char c, void* arg) -> Result<void> {
StringFormatInfo* info_arg = (StringFormatInfo*)arg;
if (!info_arg->remaining) return {};
*(info_arg->buffer) = c;
info_arg->buffer++;
info_arg->remaining--;
return {};
},
&info, ap));
*(info.buffer) = 0;
return result;
}
Result<usize> string_format(char* buf, size_t max, const char* format, ...)
{
va_list ap;
va_start(ap, format);
usize result = TRY(vstring_format(buf, max, format, ap));
va_end(ap);
return result;
}

View File

@ -6,3 +6,5 @@
typedef Result<void> (*callback_t)(char, void*);
Result<usize> cstyle_format(const char* format, callback_t callback, void* arg, va_list ap);
Result<usize> vstring_format(char* buf, size_t max, const char* format, va_list ap);
Result<usize> string_format(char* buf, size_t max, const char* format, ...);