-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpg_color.c
119 lines (97 loc) · 2.05 KB
/
pg_color.c
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/*
* pg_color: Color data type for PostgreSQL
*
* Author: Burak Yucesoy <[email protected]>
*/
#include "postgres.h"
#include "utils/elog.h"
#include "utils/palloc.h"
#include "utils/builtins.h"
#include "libpq/pqformat.h"
#ifndef PG_VERSION_NUM
#error "Unsupported too old PostgreSQL version"
#endif
#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif
#define COLOR_LENGTH 6
#define MAX_COLOR_VALUE 16777215
typedef int32 color;
static inline
int hex_to_binary(char h)
{
if (h >= '0' && h <= '9')
{
return h - '0';
}
else if (h >= 'A' && h <= 'F')
{
return h + 10 - 'A';
}
else
{
elog(ERROR, "value '%c' is not a valid digit for type color.", h);
}
return 0;
}
static inline
char binary_to_hex(int b)
{
char lookup_table[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
if (b < 0 || b > 15)
{
elog(ERROR, "value '%d' is not a valid binary representation of a hex character", b);
}
return lookup_table[b];
}
static inline
color color_from_str(const char *str)
{
int i = 0;
color c = 0;
if(strlen(str) != COLOR_LENGTH)
{
ereport(ERROR,
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
errmsg("value \"%s\" is out of range for type color", str)));
}
for(i = 0; i < COLOR_LENGTH; i++) {
c <<= 4;
c |= hex_to_binary(str[i]);
}
return c;
}
static inline
char *color_to_str(color c)
{
int i = 0;
char *str = palloc0((COLOR_LENGTH + 1) * sizeof(char));
if(c > MAX_COLOR_VALUE)
{
ereport(ERROR,
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
errmsg("value \"%d\" is out of range for type color", c)));
}
for(i = COLOR_LENGTH - 1; i >= 0; i--)
{
str[i] = binary_to_hex(c & 15);
c >>= 4;
}
return str;
}
Datum color_in(PG_FUNCTION_ARGS);
Datum color_out(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(color_in);
Datum
color_in(PG_FUNCTION_ARGS)
{
char *str = PG_GETARG_CSTRING(0);
PG_RETURN_INT32(color_from_str(str));
}
PG_FUNCTION_INFO_V1(color_out);
Datum
color_out(PG_FUNCTION_ARGS)
{
color c = PG_GETARG_INT32(0);
PG_RETURN_CSTRING(color_to_str(c));
}