From e43b27a3fa4b5649a045d5d5d0fa2b7915a96843 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Sat, 3 Aug 2019 11:32:37 +0200 Subject: [PATCH] LibDraw: Add Color::from_string(StringView) This parses hex colors in either #RRGGBBAA or #RRGGBB format. No other formats are supported at the moment. --- Libraries/LibDraw/Color.cpp | 42 ++++++++++++++++++++++++++++++++++++- Libraries/LibDraw/Color.h | 2 ++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/Libraries/LibDraw/Color.cpp b/Libraries/LibDraw/Color.cpp index 00a312b7bbb..3a54c36f1db 100644 --- a/Libraries/LibDraw/Color.cpp +++ b/Libraries/LibDraw/Color.cpp @@ -1,5 +1,7 @@ -#include "Color.h" #include +#include +#include +#include Color::Color(NamedColor named) { @@ -79,3 +81,41 @@ String Color::to_string() const { return String::format("#%b%b%b%b", red(), green(), blue(), alpha()); } + +Optional Color::from_string(const StringView& string) +{ + if (string.is_empty()) + return {}; + + if (string[0] != '#') + return {}; + + if (string.length() != 7 && string.length() != 9) + return {}; + + auto hex_nibble_to_u8 = [](char nibble) -> Optional { + if (!isxdigit(nibble)) + return {}; + if (nibble >= '0' && nibble <= '9') + return nibble - '0'; + return 10 + (tolower(nibble) - 'a'); + }; + + auto to_hex = [&](char c1, char c2) -> Optional { + auto nib1 = hex_nibble_to_u8(c1); + auto nib2 = hex_nibble_to_u8(c2); + if (!nib1.has_value() || !nib2.has_value()) + return {}; + return nib1.value() << 4 | nib2.value(); + }; + + Optional r = to_hex(string[1], string[2]); + Optional g = to_hex(string[3], string[4]); + Optional b = to_hex(string[5], string[6]); + Optional a = string.length() == 9 ? to_hex(string[7], string[8]) : Optional(255); + + if (!r.has_value() || !g.has_value() || !b.has_value() || !a.has_value()) + return {}; + + return Color(r.value(), g.value(), b.value(), a.value()); +} diff --git a/Libraries/LibDraw/Color.h b/Libraries/LibDraw/Color.h index d6c86e35a86..710b28dca8b 100644 --- a/Libraries/LibDraw/Color.h +++ b/Libraries/LibDraw/Color.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include typedef u32 RGBA32; @@ -132,6 +133,7 @@ public: } String to_string() const; + static Optional from_string(const StringView&); private: explicit Color(RGBA32 rgba)