summaryrefslogtreecommitdiff
path: root/Libraries/LibDraw
diff options
context:
space:
mode:
authorAndreas Kling <awesomekling@gmail.com>2019-08-03 11:32:37 +0200
committerAndreas Kling <awesomekling@gmail.com>2019-08-03 11:33:34 +0200
commite43b27a3fa4b5649a045d5d5d0fa2b7915a96843 (patch)
treee844e3c170dfdb667cc846d7d941b3b4ca23a1f3 /Libraries/LibDraw
parentf511421aaaffcd9dab236fa7bf9e15bb19c3a2a0 (diff)
downloadserenity-e43b27a3fa4b5649a045d5d5d0fa2b7915a96843.zip
LibDraw: Add Color::from_string(StringView)
This parses hex colors in either #RRGGBBAA or #RRGGBB format. No other formats are supported at the moment.
Diffstat (limited to 'Libraries/LibDraw')
-rw-r--r--Libraries/LibDraw/Color.cpp42
-rw-r--r--Libraries/LibDraw/Color.h2
2 files changed, 43 insertions, 1 deletions
diff --git a/Libraries/LibDraw/Color.cpp b/Libraries/LibDraw/Color.cpp
index 00a312b7bb..3a54c36f1d 100644
--- a/Libraries/LibDraw/Color.cpp
+++ b/Libraries/LibDraw/Color.cpp
@@ -1,5 +1,7 @@
-#include "Color.h"
#include <AK/Assertions.h>
+#include <LibDraw/Color.h>
+#include <ctype.h>
+#include <stdio.h>
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> 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<u8> {
+ 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<u8> {
+ 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<u8> r = to_hex(string[1], string[2]);
+ Optional<u8> g = to_hex(string[3], string[4]);
+ Optional<u8> b = to_hex(string[5], string[6]);
+ Optional<u8> a = string.length() == 9 ? to_hex(string[7], string[8]) : Optional<u8>(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 d6c86e35a8..710b28dca8 100644
--- a/Libraries/LibDraw/Color.h
+++ b/Libraries/LibDraw/Color.h
@@ -1,6 +1,7 @@
#pragma once
#include <AK/AKString.h>
+#include <AK/Optional.h>
#include <AK/Types.h>
typedef u32 RGBA32;
@@ -132,6 +133,7 @@ public:
}
String to_string() const;
+ static Optional<Color> from_string(const StringView&);
private:
explicit Color(RGBA32 rgba)