Line data Source code
1 : #include "RgbColor.h"
2 : #include <cstdint>
3 : #include <charconv>
4 : #include <stdexcept>
5 :
6 : namespace Odb::Lib::FileModel::Design
7 : {
8 3133 : RgbColor::RgbColor()
9 3133 : : red(0)
10 3133 : , green(0)
11 3133 : , blue(0)
12 3133 : , noPreference(false)
13 : {
14 3133 : }
15 :
16 3120 : RgbColor::RgbColor(const std::string& str)
17 3120 : : RgbColor()
18 : {
19 3120 : from_string(str);
20 3120 : }
21 :
22 6021 : bool RgbColor::from_string(const std::string& str)
23 : {
24 6021 : if (str.length() == 6)
25 : {
26 : // parse each two-digit component with from_chars: full
27 : // consumption (rejects "-1", "+1", "1x"), no exceptions, and
28 : // an explicit [0,100] domain check on the result
29 966 : int components[3] = { 0, 0, 0 };
30 3854 : for (int i = 0; i < 3; ++i)
31 : {
32 2892 : const auto* first = str.data() + i * 2;
33 2892 : const auto* last = first + 2;
34 2892 : const auto [ptr, ec] = std::from_chars(first, last, components[i]);
35 2892 : if (ec != std::errc() || ptr != last || components[i] < 0 || components[i] > 100)
36 : {
37 4 : return false;
38 : }
39 : }
40 :
41 962 : red = static_cast<uint8_t>(components[0]);
42 962 : green = static_cast<uint8_t>(components[1]);
43 962 : blue = static_cast<uint8_t>(components[2]);
44 962 : noPreference = false;
45 962 : return true;
46 : }
47 5055 : else if (str.length() == 1)
48 : {
49 5055 : if (str[0] == '0')
50 : {
51 5055 : noPreference = true;
52 5055 : return true;
53 : }
54 : }
55 :
56 0 : return false;
57 : }
58 :
59 6 : std::string RgbColor::to_string() const
60 : {
61 6 : if (noPreference)
62 : {
63 2 : return "0";
64 : }
65 : else
66 : {
67 : // each component is a two-digit zero-padded decimal, so the
68 : // concatenation is exactly the six-character form from_string
69 : // parses (e.g. (6, 6, 6) -> "060606", not "666")
70 : // the six-character form holds exactly two digits per component;
71 : // a value of 100 is unrepresentable and must fail loudly rather
72 : // than emit a three-digit run our own parser rejects
73 5 : if (red > 99 || green > 99 || blue > 99)
74 : {
75 1 : throw std::domain_error("color component of 100 is not representable in the two-digit ODB COLOR form");
76 : }
77 12 : auto twoDigits = [](uint8_t value) -> std::string
78 : {
79 12 : if (value < 10) return "0" + std::to_string(value);
80 4 : return std::to_string(value);
81 : };
82 4 : return twoDigits(red) + twoDigits(green) + twoDigits(blue);
83 : }
84 : }
85 : }
|