herald  2.0.0
uuid.h
1 // Copyright 2020-2021 Herald Project Contributors
2 // SPDX-License-Identifier: Apache-2.0
3 //
4 
5 #ifndef HERALD_UUID_H
6 #define HERALD_UUID_H
7 
8 #include "error_code.h"
9 #include "randomness.h"
10 
11 #include <string>
12 #include <array>
13 
14 namespace herald {
15 namespace datatype {
16 
17 // High level UUID class template
18 class UUID {
19 public:
20  using value_type = uint8_t;
21 
22  static UUID fromString(const std::string& from) noexcept;
23  // static UUID fromString(const char* from) noexcept;
24 
25  template <typename RandomnessSourceT>
26  static UUID random(RandomnessGenerator<RandomnessSourceT>& from) noexcept {
27  std::array<value_type, 16> data{ {0} };
28  Data randomness;
29  from.nextBytes(16,randomness);
30  for (std::size_t i = 0;i < 16;i++) {
31  data[i] = (value_type)randomness.at(i);
32  }
33  // Now set bits for v4 UUID explicitly
34  constexpr value_type M = 0x40; // 7th byte = 0100 in binary for MSB 0000 for LSB - v4 UUID
35  constexpr value_type N = 0x80; // 9th byte = 1000 in binary for MSB 0000 for LSB - variant 1
36  data[6] = (0x0f & data[6]) | M; // blanks out first 4 bits
37  data[8] = (0x3f & data[8]) | N; // blanks out first 2 bits
38  UUID uuid(data,false); // TODO generate random data and tag as v4
39  return uuid; // returns copy
40  }
41 
42  UUID(const char* from) noexcept;
43  UUID(UUID&& from) noexcept;
44  UUID(const UUID& from) noexcept;
45  ~UUID() noexcept = default;
46 
47  UUID& operator=(const UUID& other) noexcept; // copy assign
48 
49  bool valid() const noexcept;
50 
51  bool operator==(const UUID& other) const noexcept;
52  bool operator!=(const UUID& other) const noexcept;
53  bool operator<(const UUID& other) const noexcept;
54  bool operator<=(const UUID& other) const noexcept;
55  bool operator>(const UUID& other) const noexcept;
56  bool operator>=(const UUID& other) const noexcept;
57  // std::string operator=(const UUID& from) const noexcept; // TODO verify this syntax/location
58 
59  std::array<value_type, 16> data() const noexcept;
60  std::string string() const noexcept;
61 
62 private:
63  std::array<value_type, 16> mData = { {0}};
64  bool mValid;
65 
66  UUID(std::array<value_type, 16> data, bool isValid) noexcept;
67 };
68 
69 
70 
71 } // end namespace
72 } // end namespace
73 
74 #endif
The main data workhorse class of the Herald API.
Definition: data.h:33
std::byte at(std::size_t index) const
Returns the individual byte at index position, or a byte value of zero if index is out of bounds.
Definition: data.h:178
Definition: randomness.h:126
Definition: uuid.h:18
Acts as a non-global memory arena for arbitrary classes.
Definition: aggregates.h:15