Move to kernel style SPDX license identifiers
[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 BT_HIDDEN
20 void bt_uuid_generate(bt_uuid_t uuid_out)
21 {
22 int i;
23 GRand *rand;
24
25 BT_ASSERT(uuid_out);
26
27 rand = g_rand_new();
28
29 /*
30 * Generate 16 bytes of random bits.
31 */
32 for (i = 0; i < BT_UUID_LEN; i++) {
33 uuid_out[i] = (uint8_t) g_rand_int(rand);
34 }
35
36 /*
37 * Set the two most significant bits (bits 6 and 7) of the
38 * clock_seq_hi_and_reserved to zero and one, respectively.
39 */
40 uuid_out[8] &= ~(1 << 6);
41 uuid_out[8] |= (1 << 7);
42
43 /*
44 * Set the four most significant bits (bits 12 through 15) of the
45 * time_hi_and_version field to the 4-bit version number from
46 * Section 4.1.3.
47 */
48 uuid_out[6] &= 0x0f;
49 uuid_out[6] |= (BT_UUID_VER << 4);
50
51 g_rand_free(rand);
52 }
53
54 BT_HIDDEN
55 void bt_uuid_to_str(const bt_uuid_t uuid_in, char *str_out)
56 {
57 BT_ASSERT_DBG(uuid_in);
58 BT_ASSERT_DBG(str_out);
59
60 sprintf(str_out, BT_UUID_FMT, BT_UUID_FMT_VALUES(uuid_in));
61 }
62
63 BT_HIDDEN
64 int bt_uuid_from_str(const char *str_in, bt_uuid_t uuid_out)
65 {
66 int ret = 0;
67 bt_uuid_t uuid_scan;
68
69 BT_ASSERT_DBG(uuid_out);
70 BT_ASSERT_DBG(str_in);
71
72 if (strnlen(str_in, BT_UUID_STR_LEN + 1) != BT_UUID_STR_LEN) {
73 ret = -1;
74 goto end;
75 }
76
77 /* Scan to a temporary location in case of a partial match. */
78 if (sscanf(str_in, BT_UUID_FMT, BT_UUID_SCAN_VALUES(uuid_scan)) != BT_UUID_LEN) {
79 ret = -1;
80 }
81
82 bt_uuid_copy(uuid_out, uuid_scan);
83 end:
84 return ret;
85 }
86
87 BT_HIDDEN
88 int bt_uuid_compare(const bt_uuid_t uuid_a, const bt_uuid_t uuid_b)
89 {
90 return memcmp(uuid_a, uuid_b, BT_UUID_LEN);
91 }
92
93 BT_HIDDEN
94 void bt_uuid_copy(bt_uuid_t uuid_dest, const bt_uuid_t uuid_src)
95 {
96 BT_ASSERT(uuid_dest);
97 BT_ASSERT(uuid_src);
98 BT_ASSERT(uuid_dest != uuid_src);
99
100 memcpy(uuid_dest, uuid_src, BT_UUID_LEN);
101 }
This page took 0.030539 seconds and 4 git commands to generate.