]> git.ipfire.org Git - thirdparty/squid.git/blob - src/base/RandomUuid.h
Source Format Enforcement (#1234)
[thirdparty/squid.git] / src / base / RandomUuid.h
1 /*
2 * Copyright (C) 1996-2023 The Squid Software Foundation and contributors
3 *
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
7 */
8
9 #ifndef SQUID_SRC_BASE_RANDOMUUID_H
10 #define SQUID_SRC_BASE_RANDOMUUID_H
11
12 #include <array>
13 #include <iosfwd>
14
15 /// 128-bit Universally Unique IDentifier (UUID), version 4 (variant 1) as
16 /// defined by RFC 4122. These UUIDs are generated from pseudo-random numbers.
17 class RandomUuid
18 {
19 public:
20 /// UUID representation independent of machine byte-order architecture
21 using Serialized = std::array<uint8_t, 128/8>;
22
23 /// creates a new unique ID (i.e. not a "nil UUID" in RFC 4122 terminology)
24 RandomUuid();
25
26 /// imports a UUID value that was exported using the serialize() API
27 explicit RandomUuid(const Serialized &);
28
29 RandomUuid(RandomUuid &&) = default;
30 RandomUuid &operator=(RandomUuid &&) = default;
31
32 // (Implicit) public copying is prohibited to prevent accidental duplication
33 // of supposed-to-be-unique values. Use clone() when duplication is needed.
34 RandomUuid &operator=(const RandomUuid &) = delete;
35
36 /// exports UUID value; suitable for long-term storage
37 Serialized serialize() const;
38
39 bool operator ==(const RandomUuid &) const;
40 bool operator !=(const RandomUuid &other) const { return !(*this == other); }
41
42 /// creates a UUID object with the same value as this UUID
43 RandomUuid clone() const { return *this; }
44
45 /// writes a human-readable representation
46 void print(std::ostream &os) const;
47
48 private:
49 RandomUuid(const RandomUuid &) = default;
50
51 /// read/write access to storage bytes
52 char *raw() { return reinterpret_cast<char*>(this); }
53
54 /// read-only access to storage bytes
55 const char *raw() const { return reinterpret_cast<const char*>(this); }
56
57 /// whether this (being constructed) object follows UUID version 4 variant 1 format
58 bool sane() const;
59
60 /*
61 * These field sizes and names come from RFC 4122 Section 4.1.2. They do not
62 * accurately represent the actual UUID version 4 structure which, the six
63 * version/variant bits aside, contains just random bits.
64 */
65 uint32_t timeLow;
66 uint16_t timeMid;
67 uint16_t timeHiAndVersion;
68 uint8_t clockSeqHiAndReserved;
69 uint8_t clockSeqLow;
70 uint8_t node[6];
71 };
72
73 std::ostream &operator<<(std::ostream &os, const RandomUuid &uuid);
74
75 #endif /* SQUID_SRC_BASE_RANDOMUUID_H */
76