Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion rawterm/color.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,18 @@ namespace rawterm {
blue = static_cast<unsigned int>(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);

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";
Expand Down
3 changes: 2 additions & 1 deletion rawterm/color.h
Original file line number Diff line number Diff line change
Expand Up @@ -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) + ";" +
Expand Down
11 changes: 11 additions & 0 deletions tests/color_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
Loading