libluna: Add String::format

This commit is contained in:
apio 2023-04-07 10:37:00 +02:00
parent e6c4ceb18f
commit 9b8996adeb
Signed by: apio
GPG Key ID: B8A7D06E42258954
4 changed files with 48 additions and 14 deletions

View File

@ -1,6 +1,7 @@
#pragma once
#include <luna/Result.h>
#include <luna/StringView.h>
#include <stdarg.h>
class String
{
@ -22,6 +23,9 @@ class String
Result<String> substring(usize begin, usize size) const;
static Result<String> format(const String& fmt, ...);
static Result<String> format(StringView fmt, ...);
static Result<String> from_cstring(const char* str);
const char* chars() const
@ -75,4 +79,6 @@ class String
bool m_inline { true };
usize m_length { 0 };
static Result<String> vformat(StringView fmt, va_list ap);
};

View File

@ -2,5 +2,4 @@
#include <luna/Result.h>
#include <luna/String.h>
usize to_dynamic_unit_cstr(usize value, char* buffer, usize max);
Result<String> to_dynamic_unit(usize value);

View File

@ -1,6 +1,8 @@
#include <luna/Alloc.h>
#include <luna/CString.h>
#include <luna/Format.h>
#include <luna/String.h>
#include <luna/Vector.h>
String::String()
{
@ -61,6 +63,43 @@ const char& String::operator[](usize index) const
return chars()[index];
}
Result<String> String::format(const String& fmt, ...)
{
va_list ap;
va_start(ap, fmt);
auto rc = vformat(fmt.view(), ap);
va_end(ap);
return rc;
}
Result<String> String::format(StringView fmt, ...)
{
va_list ap;
va_start(ap, fmt);
auto rc = vformat(fmt, ap);
va_end(ap);
return rc;
}
Result<String> String::vformat(StringView fmt, va_list ap)
{
Vector<char> buf;
TRY(cstyle_format(
fmt.chars(), [](char c, void* data) -> Result<void> { return ((Vector<char>*)data)->try_append(c); }, &buf,
ap));
TRY(buf.try_append(0));
return from_cstring(buf.data());
}
Result<String> String::from_cstring(const char* str)
{
usize len = strlen(str);

View File

@ -1,12 +1,11 @@
#include <luna/Alloc.h>
#include <luna/Format.h>
#include <luna/Result.h>
#include <luna/ScopeGuard.h>
#include <luna/Units.h>
usize to_dynamic_unit_cstr(usize value, char* buffer, usize max)
Result<String> to_dynamic_unit(usize value)
{
if (value < 1024) { return string_format(buffer, max, "%zu bytes", value); }
if (value < 1024) { return String::format("%zu bytes"_sv, value); }
const char* unit_prefixes = "KMGTPE";
while (value > (1024 * 1024))
@ -15,14 +14,5 @@ usize to_dynamic_unit_cstr(usize value, char* buffer, usize max)
unit_prefixes++;
}
return string_format(buffer, max, "%zu.%zu %ciB", value / 1024, (value % 1024) / 103, *unit_prefixes);
}
Result<String> to_dynamic_unit(usize value)
{
char* const buf = TRY(make_array<char>(64));
to_dynamic_unit_cstr(value, buf, 64);
return String { buf };
return String::format("%zu.%zu %ciB"_sv, value / 1024, (value % 1024) / 103, *unit_prefixes);
}