forked from ssimicro/lib_mysqludf_amqp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
uuid.c
50 lines (39 loc) · 1.08 KB
/
uuid.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
#include "config.h"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if HAVE_LIBBSD == 1
#include <bsd/stdlib.h>
#endif /* HAVE_LIBBSD */
#define UUID_BUF_LEN 40
/*
* simple implementation of version 4 UUID generation
*/
char*
uuidgen(void)
{
int i;
int pos;
char *buffer = malloc(UUID_BUF_LEN);
if (buffer == NULL) {
return NULL;
}
memset(buffer, '\0', UUID_BUF_LEN);
for (i = 0, pos = 0; i < 16 && pos < UUID_BUF_LEN - 1; i++) {
uint8_t r = (uint8_t) arc4random();
/* set some special bits */
if (i == 6) {
r = (uint8_t) ((r & 0x0F) | 0x40); /* set version number */
} else if (i == 8) {
r = (uint8_t) ((r & 0x3F) | 0x80); /* set reserved to b01 */
}
/* insert '-' where needed */
if (pos == 8 || pos == 13 || pos == 18 || pos == 23) {
pos += snprintf(buffer + pos, UUID_BUF_LEN - pos, "-");
}
/* print hex characters */
pos += snprintf(buffer + pos, UUID_BUF_LEN - pos, "%2.2x", r);
}
return buffer;
}