1#include "color.h"
2#include "system.h"
3
4template<typename T>
5std::optional<T> color_parse(const char *pStr)
6{
7 if(!str_isallnum_hex(str: pStr))
8 return {};
9
10 const unsigned Num = str_toulong_base(str: pStr, base: 16);
11
12 T Color;
13 switch(str_length(str: pStr))
14 {
15 case 3:
16 Color.x = (((Num >> 8) & 0x0F) + ((Num >> 4) & 0xF0)) / 255.0f;
17 Color.y = (((Num >> 4) & 0x0F) + ((Num >> 0) & 0xF0)) / 255.0f;
18 Color.z = (((Num >> 0) & 0x0F) + ((Num << 4) & 0xF0)) / 255.0f;
19 Color.a = 1.0f;
20 return Color;
21
22 case 4:
23 Color.x = (((Num >> 12) & 0x0F) + ((Num >> 8) & 0xF0)) / 255.0f;
24 Color.y = (((Num >> 8) & 0x0F) + ((Num >> 4) & 0xF0)) / 255.0f;
25 Color.z = (((Num >> 4) & 0x0F) + ((Num >> 0) & 0xF0)) / 255.0f;
26 Color.a = (((Num >> 0) & 0x0F) + ((Num << 4) & 0xF0)) / 255.0f;
27 return Color;
28
29 case 6:
30 Color.x = ((Num >> 16) & 0xFF) / 255.0f;
31 Color.y = ((Num >> 8) & 0xFF) / 255.0f;
32 Color.z = ((Num >> 0) & 0xFF) / 255.0f;
33 Color.a = 1.0f;
34 return Color;
35
36 case 8:
37 Color.x = ((Num >> 24) & 0xFF) / 255.0f;
38 Color.y = ((Num >> 16) & 0xFF) / 255.0f;
39 Color.z = ((Num >> 8) & 0xFF) / 255.0f;
40 Color.a = ((Num >> 0) & 0xFF) / 255.0f;
41 return Color;
42
43 default:
44 return {};
45 }
46}
47
48template std::optional<ColorRGBA> color_parse<ColorRGBA>(const char *);
49