From 6a0583b44bca725b00579deeb1b04c70c4c028bc Mon Sep 17 00:00:00 2001 From: NaifBanana <30419422+NaifBanana@users.noreply.github.com> Date: Fri, 12 Dec 2025 02:19:45 -0600 Subject: [PATCH] Smarter SmartText (not fully working) --- include/SmartStreams.hpp | 35 +++++++++++++++++++++++++--------- tests/SmartStreamTest/main.cpp | 7 ++++++- 2 files changed, 32 insertions(+), 10 deletions(-) diff --git a/include/SmartStreams.hpp b/include/SmartStreams.hpp index bb4ed6a..8b974ff 100644 --- a/include/SmartStreams.hpp +++ b/include/SmartStreams.hpp @@ -10,12 +10,12 @@ namespace nb { -typedef std::pair SmartTextKV; +typedef std::pair SmartFormat; -//template +template struct SmartText { - std::string msg; - SmartTextKV kv = {0, ""}; + T msg; + SmartFormat fmt; }; typedef std::string (*SmartTextFormatter)(std::string, std::string); @@ -25,7 +25,7 @@ typedef std::unordered_map SmartFormatMap; template class SmartOStreamBase { public: - virtual void process(const SmartText&) = 0; + virtual void process(const SmartText&) = 0; static const SmartFormatMap Formatters; @@ -81,7 +81,23 @@ public: *_ostream << val; } - virtual void process(const SmartText&); + template + void process(const SmartText& msg) { + using D = typename std::conditional::value, SmartOStream, Derived>::type; + try { + *_ostream << D::Formatters.at(msg.fmt.first)( + static_cast(this)->process(static_cast(msg.msg)), + msg.fmt.second + ); + } catch (const std::out_of_range& e) { + *_ostream << D::Formatters.at(0)( + static_cast(this)->process(static_cast(msg.msg)), + msg.fmt.second + ); + } + } + + virtual void process(const SmartText&); static const SmartFormatMap Formatters; @@ -106,12 +122,13 @@ SmartOStream& operator<<(SmartOStream& stream, const U& msg) { } template -void SmartOStream::process(const SmartText& msg) { +void SmartOStream::process(const SmartText& msg) { using Derived = typename std::conditional::value, SmartOStream, D>::type; + std::string msg_str(msg.msg); try { - *_ostream << Derived::Formatters.at(msg.kv.first)(msg.msg, msg.kv.second); + *_ostream << Derived::Formatters.at(msg.fmt.first)(msg_str, msg.fmt.second); } catch (const std::out_of_range& e) { - *_ostream << Derived::Formatters.at(0)(msg.msg, msg.kv.second); + *_ostream << Derived::Formatters.at(0)(msg_str, msg.fmt.second); } } diff --git a/tests/SmartStreamTest/main.cpp b/tests/SmartStreamTest/main.cpp index ef0e757..4d26296 100644 --- a/tests/SmartStreamTest/main.cpp +++ b/tests/SmartStreamTest/main.cpp @@ -23,13 +23,18 @@ const nb::SmartFormatMap TestStream::Formatters = { }}, {2, [](std::string msg, std::string fmt){ return "\x1b[1m" + msg + "\x1b[0m"; + }}, + {3, [](std::string msg, std::string fmt){ + return "\x1b[31m" + msg + "\x1b[0m"; }} }; +using nb::SmartText; + int main() { auto tout = TestStream(std::cout); - tout << nb::SmartText{"Gloop!\n", {2, "32"}}; + tout << SmartText>{SmartText{"Gloop\n", {3, ""}}, {2, "32"}}; tout << 8989 << "\n"; return 0;