summaryrefslogtreecommitdiff
path: root/src/color.c
blob: 4b6b3567501d21090ecb4e67ee2d4c03784ee9ce (plain)
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
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include "color.h"
#include "log.h"

struct color hex_to_color(const char *hex)
{
	if (hex[0] == '#') {
		hex++;
	}

	uint32_t val = 0;
	int64_t tmp;
	size_t len = strlen(hex);

	errno = 0;
	if (len == 3) {
		char str[] = {
			hex[0], hex[0],
			hex[1], hex[1],
			hex[2], hex[2],
			'\0'};
		char *endptr;
		tmp = strtol(str, &endptr, 16);
		if (errno || *endptr != '\0' || tmp < 0) {
			return (struct color) { -1, -1, -1, -1 };
		}
		val = tmp;
		val <<= 8;
		val |= 0xFFu;
	} else if (len == 4) {
		char str[] = {
			hex[0], hex[0],
			hex[1], hex[1],
			hex[2], hex[2],
			hex[3], hex[3],
			'\0'};
		char *endptr;
		tmp = strtol(str, &endptr, 16);
		if (errno || *endptr != '\0' || tmp < 0) {
			return (struct color) { -1, -1, -1, -1 };
		}
		val = tmp;
	} else if (len == 6) {
		char *endptr;
		tmp = strtol(hex, &endptr, 16);
		if (errno || *endptr != '\0' || tmp < 0) {
			return (struct color) { -1, -1, -1, -1 };
		}
		val = tmp;
		val <<= 8;
		val |= 0xFFu;
	} else if (len == 8) {
		char *endptr;
		tmp = strtol(hex, &endptr, 16);
		if (errno || *endptr != '\0' || tmp < 0) {
			return (struct color) { -1, -1, -1, -1 };
		}
		val = tmp;
	} else {
		return (struct color) { -1, -1, -1, -1 };
	}

	return (struct color) {
		.r = (float)((val & 0xFF000000u) >> 24) / 255.0f,
		.g = (float)((val & 0x00FF0000u) >> 16) / 255.0f,
		.b = (float)((val & 0x0000FF00u) >> 8)  / 255.0f,
		.a = (float)((val & 0x000000FFu) >> 0)  / 255.0f,
	};
}