OdbDesign
OdbDesign ODB++ Parser - C++ library, gRPC/REST server, CLI, tests
 
Loading...
Searching...
No Matches
RgbColor.cpp
Go to the documentation of this file.
1#include "RgbColor.h"
2#include <cstdint>
3#include <charconv>
4#include <stdexcept>
5
7{
9 : red(0)
10 , green(0)
11 , blue(0)
12 , noPreference(false)
13 {
14 }
15
16 RgbColor::RgbColor(const std::string& str)
17 : RgbColor()
18 {
19 from_string(str);
20 }
21
22 bool RgbColor::from_string(const std::string& str)
23 {
24 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 int components[3] = { 0, 0, 0 };
30 for (int i = 0; i < 3; ++i)
31 {
32 const auto* first = str.data() + i * 2;
33 const auto* last = first + 2;
34 const auto [ptr, ec] = std::from_chars(first, last, components[i]);
35 if (ec != std::errc() || ptr != last || components[i] < 0 || components[i] > 100)
36 {
37 return false;
38 }
39 }
40
41 red = static_cast<uint8_t>(components[0]);
42 green = static_cast<uint8_t>(components[1]);
43 blue = static_cast<uint8_t>(components[2]);
44 noPreference = false;
45 return true;
46 }
47 else if (str.length() == 1)
48 {
49 if (str[0] == '0')
50 {
51 noPreference = true;
52 return true;
53 }
54 }
55
56 return false;
57 }
58
59 std::string RgbColor::to_string() const
60 {
61 if (noPreference)
62 {
63 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 if (red > 99 || green > 99 || blue > 99)
74 {
75 throw std::domain_error("color component of 100 is not representable in the two-digit ODB COLOR form");
76 }
77 auto twoDigits = [](uint8_t value) -> std::string
78 {
79 if (value < 10) return "0" + std::to_string(value);
80 return std::to_string(value);
81 };
82 return twoDigits(red) + twoDigits(green) + twoDigits(blue);
83 }
84 }
85}
bool from_string(const std::string &str)
Definition RgbColor.cpp:22