Move userspace to a templated StrFormat.

This commit is contained in:
Drew Galbraith 2023-11-03 02:48:21 -07:00
parent d9df1212b7
commit 26b61db021
25 changed files with 263 additions and 217 deletions

View file

@ -0,0 +1,73 @@
#include "glacier/string/str_format.h"
namespace glcr {
namespace {
void StrFormatNumber(StringBuilder& builder, uint64_t value, uint64_t base) {
const char* kHexCharacters = "0123456789ABCDEF";
if (value < base) {
builder.PushBack(kHexCharacters[value]);
return;
}
StrFormatNumber(builder, value / base, base);
builder.PushBack(kHexCharacters[value % base]);
}
} // namespace
template <>
void StrFormatValue(StringBuilder& builder, uint8_t value, StringView opts) {
StrFormatValue(builder, static_cast<uint64_t>(value), opts);
}
template <>
void StrFormatValue(StringBuilder& builder, uint16_t value, StringView opts) {
StrFormatValue(builder, static_cast<uint64_t>(value), opts);
}
template <>
void StrFormatValue(StringBuilder& builder, int32_t value, StringView opts) {
StrFormatValue(builder, static_cast<uint64_t>(value), opts);
}
template <>
void StrFormatValue(StringBuilder& builder, uint32_t value, StringView opts) {
StrFormatValue(builder, static_cast<uint64_t>(value), opts);
}
template <>
void StrFormatValue(StringBuilder& builder, uint64_t value, StringView opts) {
if (opts.find('x') != opts.npos) {
builder.PushBack("0x");
StrFormatNumber(builder, value, 16);
} else {
StrFormatNumber(builder, value, 10);
}
}
template <>
void StrFormatValue(StringBuilder& builder, ErrorCode value, StringView opts) {
StrFormatValue(builder, static_cast<uint64_t>(value), opts);
}
template <>
void StrFormatValue(StringBuilder& builder, const char* value,
StringView opts) {
StrFormatValue(builder, StringView(value), opts);
}
template <>
void StrFormatValue(StringBuilder& builder, StringView value, StringView opts) {
StrFormatInternal(builder, value);
}
void StrFormatInternal(StringBuilder& builder, StringView format) {
// TODO: Consider throwing an error if there are unhandled format
builder.PushBack(format);
}
} // namespace glcr