| 8 | #include "uuid.h" |
| 9 | |
| 10 | char *UUID_New() { |
| 11 | /* Implementation is based on https://www.cryptosys.net/pki/uuid-rfc4122.html */ |
| 12 | |
| 13 | // Generate 16 random bytes. |
| 14 | unsigned char r[16]; |
| 15 | int i; |
| 16 | |
| 17 | for(i = 0; i < 16; i++) { |
| 18 | r[i] = rand() % 0xff; |
| 19 | } |
| 20 | |
| 21 | char *uuid = rm_malloc(37 * sizeof(char)); |
| 22 | sprintf(uuid, "%08x-%04x-%04x-%04x-%04x%08x", |
| 23 | *((uint32_t *)r), |
| 24 | *((uint16_t *)(r + 4)), |
| 25 | // Set the four most significant bits of the 7th byte to 0100'B, so the high nibble is "4". |
| 26 | (*((uint16_t *)(r + 6)) & 0b0000111111111111) | 0b0100000000000000, |
| 27 | // Set the two most significant bits of the 9th byte to 10'B, so the high nibble will be one of "8", "9", "A", or "B" (see Note 1). |
| 28 | (*((uint16_t *)(r + 8)) & 0b0011111111111111) | 0b1000000000000000, |
| 29 | *((uint16_t *)(r + 10)), |
| 30 | *((uint32_t *)(r + 12))); |
| 31 | |
| 32 | uuid[36] = '\0'; |
| 33 | return uuid; |
| 34 | } |
no test coverage detected