plptools
Loading...
Searching...
No Matches
uuid.cc
Go to the documentation of this file.
1/*
2 * This file is part of plptools.
3 *
4 * Copyright (c) 2026 Jason Morley <hello@jbmorley.co.uk>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * along with this program; if not, see <https://www.gnu.org/licenses/>.
18 *
19 */
20#include "config.h"
21
22#include "uuid.h"
23
24#include <array>
25#include <cstdint>
26#include <cstdio>
27
28constexpr size_t kUUID4Size = 16;
29
30std::string uuid::uuid4() {
31 std::array<uint8_t, kUUID4Size> b;
32
33 FILE* f = fopen("/dev/urandom", "rb");
34 if (!f) {
35 fprintf(stderr, "Failed to open /dev/urandom while generating UUID4.\n");
36 abort();
37 }
38
39 int count = fread(b.data(), 1, kUUID4Size, f);
40 fclose(f);
41 if (count != kUUID4Size) {
42 fprintf(stderr, "Failed to read from /dev/urandom while generating UUID4.\n");
43 abort();
44 }
45
46 // Mask the version and variant into the random data.
47 b[6] = (b[6] & 0x0F) | 0x40; // 4
48 b[8] = (b[8] & 0x3F) | 0x80; // RFC 4122
49
50 char buf[37];
51 snprintf(buf, sizeof(buf),
52 "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
53 b[0], b[1], b[2], b[3],
54 b[4], b[5], b[6], b[7],
55 b[8], b[9], b[10], b[11],
56 b[12], b[13], b[14], b[15]);
57
58 return std::string(buf);
59}
std::string uuid4()
Definition: uuid.cc:30
constexpr size_t kUUID4Size
Definition: uuid.cc:28