-
Notifications
You must be signed in to change notification settings - Fork 0
/
color.cpp
58 lines (47 loc) · 1.31 KB
/
color.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include "infra/color.h"
#include "infra/exception.h"
#include "infra/string.h"
#ifdef HAVE_CHARCONV
#include <charconv>
#endif
#include <fmt/format.h>
namespace inf {
static uint8_t parse_hex(std::string_view str)
{
#ifdef HAVE_CHARCONV
uint8_t value;
auto res = std::from_chars(str.data(), str.data() + str.size(), value, 16);
if (res.ec == std::errc()) {
return value;
}
#endif
throw InvalidArgument("Invalid hex color value: {}", str);
}
Color::Color(std::string_view hexString)
{
if (hexString.empty()) {
throw InvalidArgument("Empty color string");
}
if (hexString[0] != '#' || (hexString.size() != 7 && hexString.size() != 9)) {
throw InvalidArgument("Invalid color string: {}", hexString);
}
int offset = 1;
if (hexString.size() == 9) {
a = parse_hex(hexString.substr(offset, 2));
offset += 2;
} else {
a = 255;
}
r = parse_hex(hexString.substr(offset, 2));
g = parse_hex(hexString.substr(offset + 2, 2));
b = parse_hex(hexString.substr(offset + 4, 2));
}
std::string Color::to_hex_rgb() const noexcept
{
return fmt::format(FMT_STRING("#{:02X}{:02X}{:02X}"), r, g, b);
}
std::string Color::to_hex_argb() const noexcept
{
return fmt::format(FMT_STRING("#{:02X}{:02X}{:02X}{:02X}"), a, r, g, b);
}
}