1 // (c) Dean McNamee <dean@gmail.com>, 2012.
2 // C++ port by Mapbox, Konstantin Käfer <mail@kkaefer.com>, 2014-2017.
3 //
4 // https://github.com/deanm/css-color-parser-js
5 // https://github.com/kkaefer/css-color-parser-cpp
6 //
7 // Permission is hereby granted, free of charge, to any person obtaining a copy
8 // of this software and associated documentation files (the "Software"), to
9 // deal in the Software without restriction, including without limitation the
10 // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
11 // sell copies of the Software, and to permit persons to whom the Software is
12 // furnished to do so, subject to the following conditions:
13 //
14 // The above copyright notice and this permission notice shall be included in
15 // all copies or substantial portions of the Software.
16 //
17 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
23 // IN THE SOFTWARE.
24
25 #ifndef CSS_COLOR_PARSER_CPP
26 #define CSS_COLOR_PARSER_CPP
27
28 #include <string>
29 #include <cmath>
30 #include <experimental/optional>
31
32 namespace CSSColorParser {
33
34 template <class T>
35 using optional = std::experimental::optional<T>;
36
37 struct Color {
ColorCSSColorParser::Color38 inline Color() {
39 }
ColorCSSColorParser::Color40 inline Color(unsigned char r_, unsigned char g_, unsigned char b_, float a_)
41 : r(r_), g(g_), b(b_), a(a_ > 1 ? 1 : a_ < 0 ? 0 : a_) {
42 }
43 unsigned char r = 0, g = 0, b = 0;
44 float a = 1.0f;
45 };
46
operator ==(const Color & lhs,const Color & rhs)47 inline bool operator==(const Color& lhs, const Color& rhs) {
48 return lhs.r == rhs.r && lhs.g == rhs.g && lhs.b == rhs.b && ::fabs(lhs.a - rhs.a) < 0.0001f;
49 }
50
operator !=(const Color & lhs,const Color & rhs)51 inline bool operator!=(const Color& lhs, const Color& rhs) {
52 return !(lhs == rhs);
53 }
54
55 optional<Color> parse(const std::string& css_str);
56
57 } // namespace CSSColorParser
58
59 #endif
60