diff --git a/rawterm/color.cpp b/rawterm/color.cpp index 99457a7..212fe03 100644 --- a/rawterm/color.cpp +++ b/rawterm/color.cpp @@ -24,7 +24,7 @@ namespace rawterm { blue = static_cast(std::stoi(hex.substr(5, 2), nullptr, 16)); } - const std::string Color::to_hex() { + [[nodiscard]] const std::string Color::to_hex() const noexcept { std::string r_str = std::format("{:02X}", red); std::string g_str = std::format("{:02X}", green); std::string b_str = std::format("{:02X}", blue); @@ -32,6 +32,10 @@ namespace rawterm { return "#" + r_str + g_str + b_str; } + [[nodiscard]] const std::string Color::to_str() const noexcept { + return std::to_string(red) + ";" + std::to_string(green) + ";" + std::to_string(blue) + "m"; + } + [[nodiscard]] std::string set_foreground(const std::string& s, const Color& color) { return "\x1B[38;2;" + std::to_string(color.red) + ';' + std::to_string(color.green) + ';' + std::to_string(color.blue) + 'm' + s + "\x1B[39m"; diff --git a/rawterm/color.h b/rawterm/color.h index 92baf66..6694652 100644 --- a/rawterm/color.h +++ b/rawterm/color.h @@ -13,7 +13,8 @@ namespace rawterm { Color(unsigned int x, unsigned int y, unsigned int z) : red(x), green(y), blue(z) {} Color(const std::string&); - const std::string to_hex(); + [[nodiscard]] const std::string to_hex() const noexcept; + [[nodiscard]] const std::string to_str() const noexcept; friend std::ostream& operator<<(std::ostream& os, const Color& c) { return os << std::to_string(c.red) + ";" + std::to_string(c.green) + ";" + diff --git a/tests/color_test.cpp b/tests/color_test.cpp index 1d2e8df..c09b92d 100644 --- a/tests/color_test.cpp +++ b/tests/color_test.cpp @@ -18,6 +18,17 @@ boost::ut::suite<"Color"> color_suite = [] { expect(c3.to_hex() == "#123456"); }; + "to_str"_test = [] { + rawterm::Color c; + expect(c.to_str() == "0;0;0m"); + + auto c2 = rawterm::Color("#123456"); + expect(c2.to_str() == "18;52;86m"); + + auto c3 = rawterm::Color(18, 52, 86); + expect(c3.to_str() == "18;52;86m"); + }; + "set_foreground"_test = [] { auto c = rawterm::Color(0, 255, 0); std::string expected = "\x1B[38;2;0;255;0mHello\x1B[39m";