Add string_format and vstring_format
This commit is contained in:
parent
1ed51d11cb
commit
552186ad51
@ -467,4 +467,43 @@ 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;
|
||||
}
|
@ -5,4 +5,6 @@
|
||||
|
||||
typedef Result<void> (*callback_t)(char, void*);
|
||||
|
||||
Result<usize> cstyle_format(const char* format, callback_t callback, void* arg, va_list ap);
|
||||
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, ...);
|
Loading…
Reference in New Issue
Block a user