From 552186ad51ef68589b96bb32695775a7b6cc90c2 Mon Sep 17 00:00:00 2001 From: apio Date: Wed, 30 Nov 2022 12:36:21 +0100 Subject: [PATCH] Add string_format and vstring_format --- luna/Format.cpp | 39 +++++++++++++++++++++++++++++++++++++++ luna/Format.h | 4 +++- 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/luna/Format.cpp b/luna/Format.cpp index 7d086876..f3b1c62a 100644 --- a/luna/Format.cpp +++ b/luna/Format.cpp @@ -467,4 +467,43 @@ Result cstyle_format(const char* format, callback_t callback, void* arg, } return state.count; +} + +struct StringFormatInfo +{ + char* buffer; + size_t remaining; +}; + +Result 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 { + 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 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; } \ No newline at end of file diff --git a/luna/Format.h b/luna/Format.h index 1d06050e..3ad779f2 100644 --- a/luna/Format.h +++ b/luna/Format.h @@ -5,4 +5,6 @@ typedef Result (*callback_t)(char, void*); -Result cstyle_format(const char* format, callback_t callback, void* arg, va_list ap); \ No newline at end of file +Result cstyle_format(const char* format, callback_t callback, void* arg, va_list ap); +Result vstring_format(char* buf, size_t max, const char* format, va_list ap); +Result string_format(char* buf, size_t max, const char* format, ...); \ No newline at end of file