Visibility hidden by default
[babeltrace.git] / src / common / uuid.c
1 /*
2 * SPDX-License-Identifier: MIT
3 *
4 * Copyright (C) 2019 Michael Jeanson <mjeanson@efficios.com>
5 */
6
7 #include <glib.h>
8 #include <stdio.h>
9 #include <string.h>
10 #include <inttypes.h>
11
12 #include "common/assert.h"
13 #include "common/uuid.h"
14
15
16 /*
17 * Generate a random UUID according to RFC4122, section 4.4.
18 */
19 void bt_uuid_generate(bt_uuid_t uuid_out)
20 {
21 int i;
22 GRand *rand;
23
24 BT_ASSERT(uuid_out);
25
26 rand = g_rand_new();
27
28 /*
29 * Generate 16 bytes of random bits.
30 */
31 for (i = 0; i < BT_UUID_LEN; i++) {
32 uuid_out[i] = (uint8_t) g_rand_int(rand);
33 }
34
35 /*
36 * Set the two most significant bits (bits 6 and 7) of the
37 * clock_seq_hi_and_reserved to zero and one, respectively.
38 */
39 uuid_out[8] &= ~(1 << 6);
40 uuid_out[8] |= (1 << 7);
41
42 /*
43 * Set the four most significant bits (bits 12 through 15) of the
44 * time_hi_and_version field to the 4-bit version number from
45 * Section 4.1.3.
46 */
47 uuid_out[6] &= 0x0f;
48 uuid_out[6] |= (BT_UUID_VER << 4);
49
50 g_rand_free(rand);
51 }
52
53 void bt_uuid_to_str(const bt_uuid_t uuid_in, char *str_out)
54 {
55 BT_ASSERT_DBG(uuid_in);
56 BT_ASSERT_DBG(str_out);
57
58 snprintf(str_out, BT_UUID_STR_LEN + 1, BT_UUID_FMT, BT_UUID_FMT_VALUES(uuid_in));
59 }
60
61 int bt_uuid_from_str(const char *str_in, bt_uuid_t uuid_out)
62 {
63 int ret = 0;
64 bt_uuid_t uuid_scan;
65
66 BT_ASSERT_DBG(uuid_out);
67 BT_ASSERT_DBG(str_in);
68
69 if (strnlen(str_in, BT_UUID_STR_LEN + 1) != BT_UUID_STR_LEN) {
70 ret = -1;
71 goto end;
72 }
73
74 /* Scan to a temporary location in case of a partial match. */
75 if (sscanf(str_in, BT_UUID_FMT, BT_UUID_SCAN_VALUES(uuid_scan)) != BT_UUID_LEN) {
76 ret = -1;
77 }
78
79 bt_uuid_copy(uuid_out, uuid_scan);
80 end:
81 return ret;
82 }
83
84 int bt_uuid_compare(const bt_uuid_t uuid_a, const bt_uuid_t uuid_b)
85 {
86 return memcmp(uuid_a, uuid_b, BT_UUID_LEN);
87 }
88
89 void bt_uuid_copy(bt_uuid_t uuid_dest, const bt_uuid_t uuid_src)
90 {
91 BT_ASSERT(uuid_dest);
92 BT_ASSERT(uuid_src);
93 BT_ASSERT(uuid_dest != uuid_src);
94
95 memcpy(uuid_dest, uuid_src, BT_UUID_LEN);
96 }
This page took 0.031382 seconds and 4 git commands to generate.