blob: 391474062f3ae1d5e9c11bef5dcb01d9b7781194 [file] [log] [blame]
Austin Schuh64fab802020-09-09 22:47:47 -07001#include "aos/events/logging/uuid.h"
2
Austin Schuh20ac95d2020-12-05 17:24:19 -08003#include <fcntl.h>
4#include <sys/stat.h>
5#include <sys/types.h>
Austin Schuh64fab802020-09-09 22:47:47 -07006#include <array>
7#include <random>
8#include <string_view>
9
Austin Schuh20ac95d2020-12-05 17:24:19 -080010#include "glog/logging.h"
11
Austin Schuh64fab802020-09-09 22:47:47 -070012namespace aos {
13namespace {
14char ToHex(int val) {
15 if (val < 10) {
16 return val + '0';
17 } else {
18 return val - 10 + 'a';
19 }
20}
21} // namespace
22
23UUID UUID::Random() {
24 std::random_device rd;
25 std::mt19937 gen(rd());
26
27 std::uniform_int_distribution<> dis(0, 15);
28 std::uniform_int_distribution<> dis2(8, 11);
29
30 UUID result;
31
32 // UUID4 is implemented per https://www.cryptosys.net/pki/uuid-rfc4122.html
33 int i;
34 for (i = 0; i < 8; i++) {
35 result.data_[i] = ToHex(dis(gen));
36 }
37 result.data_[i] = '-';
38 ++i;
39 for (; i < 13; i++) {
40 result.data_[i] = ToHex(dis(gen));
41 }
42 result.data_[i] = '-';
43 ++i;
44 result.data_[i] = '4';
45 ++i;
46 for (; i < 18; i++) {
47 result.data_[i] = ToHex(dis(gen));
48 }
49 result.data_[i] = '-';
50 ++i;
51 result.data_[i] = ToHex(dis2(gen));
52 ++i;
53 for (; i < 23; i++) {
54 result.data_[i] = ToHex(dis(gen));
55 }
56 result.data_[i] = '-';
57 ++i;
58 for (; i < 36; i++) {
59 result.data_[i] = ToHex(dis(gen));
60 }
61
62 return result;
63}
64
Austin Schuh20ac95d2020-12-05 17:24:19 -080065UUID UUID::Zero() { return FromString("00000000-0000-0000-0000-000000000000"); }
66
67UUID UUID::FromString(std::string_view str) {
Brian Silverman1f345222020-09-24 21:14:48 -070068 UUID result;
Austin Schuh20ac95d2020-12-05 17:24:19 -080069 CHECK_EQ(str.size(), kSize);
70
71 std::copy(str.begin(), str.end(), result.data_.begin());
72 return result;
73}
74
75UUID UUID::BootUUID() {
76 int fd = open("/proc/sys/kernel/random/boot_id", O_RDONLY);
77 PCHECK(fd != -1);
78
79 UUID result;
80 CHECK_EQ(static_cast<ssize_t>(kSize), read(fd, result.data_.begin(), kSize));
81 close(fd);
82
Brian Silverman1f345222020-09-24 21:14:48 -070083 return result;
84}
85
Austin Schuh64fab802020-09-09 22:47:47 -070086} // namespace aos