-
Notifications
You must be signed in to change notification settings - Fork 0
/
tinyuuid.c
69 lines (60 loc) · 1.42 KB
/
tinyuuid.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
#include <stdio.h>
#include <err.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "tinyuuid.h"
void tiny_uuid_generate_random(uuid_t out) {
int r;
int f = open("/dev/urandom", O_RDONLY);
if (f >= 0) {
do {
r = read(f, out, sizeof(uuid_t));
} while (r == EINTR);
close(f);
} else {
err(1, "unable to open /dev/urandom");
}
}
void tiny_uuid_unparse(uuid_t src, char *dst) {
for (int i = 0; i < 16; ++i) {
switch (i) {
case 4:
case 6:
case 8:
case 10:
*dst++ = '-';
default:
break;
}
sprintf(dst, "%02x", src[i]);
dst +=2 ;
}
*dst = '\0';
}
static inline unsigned int hex_to_int(char c) {
char d = (c >= '0' && c <= '9') ? '0' :
(c >= 'a' && c <= 'f') ? ('a' - 0xa) :
(c >= 'A' && c <= 'F') ? ('A' - 0xa) : 0;
return c - d;
}
int tiny_uuid_parse(char *src, uuid_t dst) {
for (int i = 0; i < 16; ++i) {
switch (i) {
case 4:
case 6:
case 8:
case 10:
if (*src++ != '-') {
return -1;
}
default:
break;
}
*dst++ = (hex_to_int(src[0]) << 4) | hex_to_int(src[1]);
src += 2;
}
return 0;
}