libluna: Add StringBuilder

This commit is contained in:
apio 2023-04-07 11:53:52 +02:00
parent 4c0dff9b32
commit 4e48d024d9
Signed by: apio
GPG Key ID: B8A7D06E42258954
3 changed files with 88 additions and 0 deletions

View File

@ -14,6 +14,7 @@ set(FREESTANDING_SOURCES
src/Buffer.cpp src/Buffer.cpp
src/Stack.cpp src/Stack.cpp
src/String.cpp src/String.cpp
src/StringBuilder.cpp
src/StringView.cpp src/StringView.cpp
src/Utf8.cpp src/Utf8.cpp
src/TarStream.cpp src/TarStream.cpp

View File

@ -0,0 +1,22 @@
#pragma once
#include <luna/Buffer.h>
#include <luna/String.h>
class StringBuilder
{
public:
Result<void> add(const String& value);
Result<void> add(StringView value);
Result<void> add(void* value);
Result<void> add(long value);
Result<void> add(unsigned long value);
Result<void> add(char value);
Result<void> format(StringView fmt, ...);
Result<void> vformat(StringView fmt, va_list ap);
Result<String> string();
private:
Buffer m_data;
};

View File

@ -0,0 +1,65 @@
#include <luna/Format.h>
#include <luna/StringBuilder.h>
#include <luna/Vector.h>
Result<void> StringBuilder::add(StringView value)
{
return m_data.append_data((const u8*)value.chars(), value.length());
}
Result<void> StringBuilder::add(const String& value)
{
return add(value.view());
}
Result<void> StringBuilder::add(void* value)
{
return format("%p"_sv, value);
}
Result<void> StringBuilder::add(long value)
{
return format("%li"_sv, value);
}
Result<void> StringBuilder::add(unsigned long value)
{
return format("%lu"_sv, value);
}
Result<void> StringBuilder::add(char value)
{
return format("%c"_sv, value);
}
Result<void> StringBuilder::format(StringView fmt, ...)
{
va_list ap;
va_start(ap, fmt);
auto rc = vformat(fmt, ap);
va_end(ap);
return rc;
}
Result<void> StringBuilder::vformat(StringView fmt, va_list ap)
{
Vector<char> temp;
TRY(cstyle_format(
fmt.chars(), [](char c, void* buf) -> Result<void> { return ((Vector<char>*)buf)->try_append(c); }, &temp, ap));
TRY(m_data.append_data((u8*)temp.data(), temp.size()));
return {};
}
Result<String> StringBuilder::string()
{
char nul = '\0';
TRY(m_data.append_data((u8*)&nul, 1));
return String::from_cstring((const char*)m_data.data());
}