Files
Library/include/Void/Text/Format.hpp
T
faumarayandClaude Fable 5 28b94883fd Restructure into umbrella modules (~55 -> 16 targets)
Headers move, CMake targets merge, C++ namespaces stay unchanged:
- Core: Scope, Lazy, Counted, Flags, Hash, Bits, Uuid, TypeList, TypeMap, Variant
- Functional: Pipeline, Either, Result, Retry
- Containers: Ring, Pool, PriorityQueue, LRU, Trie, Graph, DisjointSet, Bitset, Interval
- Math: +Matrix, Numeric, Random, Histogram
- Text: Str, Format, Tokenizer, Diff, Encoding, Semver
- Data: Json, Csv, Ini
- Async: Coro, Concurrency, EventBus, Observable
- Time: +Bench
- Log: Log facade + Logging framework (facade now header-only, breaking
  the Stacktrace<->Log link cycle the merge would have created)
- System: FileSystem + Process
- Configuration: +Argparse
- Unchanged: Stacktrace, Plugin, StateMachine, Testing, TestingMock, Detail

Module system fixes:
- OPTIONAL_DEPS resolution deferred to void_finalize_modules() so it no
  longer depends on the alphabetical discovery order of src/ subdirs
  (Testing -> Text would have been silently dropped).
- Every header-only module now has a tracked module.cmake; previously the
  empty src/<Name> marker dirs were untracked, so a fresh clone would have
  silently skipped those modules.
- VOID_HAS_LOGGING/CONCURRENCY/STR consumers renamed to LOG/ASYNC/TEXT.

Tests move to tests/standalone/<Umbrella>/<Feature>.cpp (Result suite files
prefixed: ResultBasic etc.). Test count verified identical (831) before and
after. README/CLAUDE.md module tables updated.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 18:50:02 +03:00

168 lines
6.0 KiB
C++

#pragma once
#include <format>
#include <stdexcept>
#include <string>
#include <string_view>
#include <unordered_map>
#include <vector>
namespace Void::Format
{
// ── Named-placeholder template rendering ──────────────────────────────────────
// render("Hello, {name}! You are {age} years old.", {{"name","Alice"},{"age","30"}})
// → "Hello, Alice! You are 30 years old."
//
// Unrecognised keys leave the placeholder untouched.
[[nodiscard]] inline std::string
render(std::string_view tmpl,
const std::unordered_map<std::string, std::string>& vars)
{
std::string out;
out.reserve(tmpl.size());
std::size_t i = 0;
while (i < tmpl.size()) {
if (tmpl[i] == '{') {
if (i + 1 < tmpl.size() && tmpl[i + 1] == '{') {
out += '{'; i += 2; continue; // escaped {{
}
const auto close = tmpl.find('}', i + 1);
if (close == std::string_view::npos) {
out += tmpl[i++]; continue; // unclosed brace — copy verbatim
}
const std::string key{tmpl.substr(i + 1, close - i - 1)};
const auto it = vars.find(key);
if (it != vars.end()) {
out += it->second;
} else {
out += '{'; out += key; out += '}';
}
i = close + 1;
} else if (tmpl[i] == '}' && i + 1 < tmpl.size() && tmpl[i+1] == '}') {
out += '}'; i += 2; // escaped }}
} else {
out += tmpl[i++];
}
}
return out;
}
// ── Positional template rendering ────────────────────────────────────────────
// render_pos("Hello, {0}! You are {1} years old.", {"Alice", "30"})
// → "Hello, Alice! You are 30 years old."
[[nodiscard]] inline std::string
render_pos(std::string_view tmpl, const std::vector<std::string>& args)
{
std::string out;
out.reserve(tmpl.size());
std::size_t i = 0;
while (i < tmpl.size()) {
if (tmpl[i] == '{') {
if (i + 1 < tmpl.size() && tmpl[i + 1] == '{') {
out += '{'; i += 2; continue;
}
const auto close = tmpl.find('}', i + 1);
if (close == std::string_view::npos) { out += tmpl[i++]; continue; }
const std::string_view key = tmpl.substr(i + 1, close - i - 1);
std::size_t idx = 0;
bool valid = !key.empty();
for (char c : key) {
if (c < '0' || c > '9') { valid = false; break; }
idx = idx * 10 + static_cast<std::size_t>(c - '0');
}
if (valid && idx < args.size()) {
out += args[idx];
} else {
out += '{'; out += key; out += '}';
}
i = close + 1;
} else {
out += tmpl[i++];
}
}
return out;
}
// ── Indent ────────────────────────────────────────────────────────────────────
// Add `indent` spaces to the beginning of every line.
[[nodiscard]] inline std::string indent(std::string_view text,
std::size_t spaces = 4)
{
const std::string prefix(spaces, ' ');
std::string out;
out.reserve(text.size() + spaces * 8);
bool start_of_line = true;
for (char c : text) {
if (start_of_line && c != '\n') { out += prefix; }
out += c;
start_of_line = (c == '\n');
}
return out;
}
// ── Word-wrap ─────────────────────────────────────────────────────────────────
// Wrap text at `width` columns, breaking at whitespace.
[[nodiscard]] inline std::string word_wrap(std::string_view text,
std::size_t width = 80)
{
std::string out;
out.reserve(text.size() + text.size() / width + 1);
std::size_t col = 0;
std::size_t i = 0;
while (i < text.size()) {
// Find next word boundary
const auto space = text.find_first_of(" \t\n", i);
const auto word_end = (space == std::string_view::npos) ? text.size() : space;
const std::size_t word_len = word_end - i;
if (col > 0 && col + 1 + word_len > width) {
out += '\n'; col = 0;
} else if (col > 0) {
out += ' '; ++col;
}
out.append(text.data() + i, word_len);
col += word_len;
i = word_end;
// Skip whitespace (normalise runs to single space/newline)
while (i < text.size() && (text[i] == ' ' || text[i] == '\t')) ++i;
if (i < text.size() && text[i] == '\n') { out += '\n'; col = 0; ++i; }
}
return out;
}
// ── Table formatting ─────────────────────────────────────────────────────────
// Format a 2-D table of strings as aligned columns separated by `sep`.
[[nodiscard]] inline std::string
format_table(const std::vector<std::vector<std::string>>& rows,
std::string_view sep = " ")
{
if (rows.empty()) return {};
const std::size_t ncols = rows[0].size();
std::vector<std::size_t> widths(ncols, 0);
for (const auto& row : rows) {
for (std::size_t c = 0; c < row.size() && c < ncols; ++c) {
widths[c] = std::max(widths[c], row[c].size());
}
}
std::string out;
for (const auto& row : rows) {
for (std::size_t c = 0; c < ncols; ++c) {
const auto& cell = c < row.size() ? row[c] : std::string{};
out += cell;
if (c + 1 < ncols) {
out.append(widths[c] - cell.size(), ' ');
out += sep;
}
}
out += '\n';
}
return out;
}
} // namespace Void::Format