1/*
2 * IXUuid.cpp
3 * Author: Benjamin Sergeant
4 * Copyright (c) 2018 Machine Zone. All rights reserved.
5 */
6
7/**
8 * Generate a random uuid similar to the uuid python module
9 *
10 * >>> import uuid
11 * >>> uuid.uuid4().hex
12 * 'bec08155b37d4050a1f3c3fa0276bf12'
13 *
14 * Code adapted from https://github.com/r-lyeh-archived/sole
15 */
16
17#include "IXUuid.h"
18
19#include <iomanip>
20#include <random>
21#include <sstream>
22#include <string>
23
24
25namespace ix
26{
27 class Uuid
28 {
29 public:
30 Uuid();
31 std::string toString() const;
32
33 private:
34 uint64_t _ab;
35 uint64_t _cd;
36 };
37
38 Uuid::Uuid()
39 {
40 static std::random_device rd;
41 static std::uniform_int_distribution<uint64_t> dist(0, (uint64_t)(~0));
42
43 _ab = dist(rd);
44 _cd = dist(rd);
45
46 _ab = (_ab & 0xFFFFFFFFFFFF0FFFULL) | 0x0000000000004000ULL;
47 _cd = (_cd & 0x3FFFFFFFFFFFFFFFULL) | 0x8000000000000000ULL;
48 }
49
50 std::string Uuid::toString() const
51 {
52 std::stringstream ss;
53 ss << std::hex << std::nouppercase << std::setfill('0');
54
55 uint32_t a = (_ab >> 32);
56 uint32_t b = (_ab & 0xFFFFFFFF);
57 uint32_t c = (_cd >> 32);
58 uint32_t d = (_cd & 0xFFFFFFFF);
59
60 ss << std::setw(8) << (a);
61 ss << std::setw(4) << (b >> 16);
62 ss << std::setw(4) << (b & 0xFFFF);
63 ss << std::setw(4) << (c >> 16);
64 ss << std::setw(4) << (c & 0xFFFF);
65 ss << std::setw(8) << d;
66
67 return ss.str();
68 }
69
70 std::string uuid4()
71 {
72 Uuid id;
73 return id.toString();
74 }
75} // namespace ix
76