| 1 | // Copyright (C) 2013-2018 by Maxim Bublis <[email protected]> |
| 2 | // |
| 3 | // Permission is hereby granted, free of charge, to any person obtaining |
| 4 | // a copy of this software and associated documentation files (the |
| 5 | // "Software"), to deal in the Software without restriction, including |
| 6 | // without limitation the rights to use, copy, modify, merge, publish, |
| 7 | // distribute, sublicense, and/or sell copies of the Software, and to |
| 8 | // permit persons to whom the Software is furnished to do so, subject to |
| 9 | // the following conditions: |
| 10 | // |
| 11 | // The above copyright notice and this permission notice shall be |
| 12 | // included in all copies or substantial portions of the Software. |
| 13 | // |
| 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, |
| 15 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF |
| 16 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND |
| 17 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE |
| 18 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION |
| 19 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION |
| 20 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 21 | |
| 22 | // Package uuid provides implementations of the Universally Unique Identifier |
| 23 | // (UUID), as specified in RFC-9562 (formerly RFC-4122). |
| 24 | // |
| 25 | // RFC-9562[1] provides the specification for versions 1, 3, 4, 5, 6, 7 and 8. |
| 26 | // |
| 27 | // DCE 1.1[2] provides the specification for version 2, but version 2 support |
| 28 | // was removed from this package in v4 due to some concerns with the |
| 29 | // specification itself. Reading the spec, it seems that it would result in |
| 30 | // generating UUIDs that aren't very unique. In having read the spec it seemed |
| 31 | // that our implementation did not meet the spec. It also seems to be at-odds |
| 32 | // with RFC 9562, meaning we would need quite a bit of special code to support |
| 33 | // it. Lastly, there were no Version 2 implementations that we could find to |
| 34 | // ensure we were understanding the specification correctly. |
| 35 | // |
| 36 | // [1] https://tools.ietf.org/html/rfc9562 |
| 37 | // [2] http://pubs.opengroup.org/onlinepubs/9696989899/chap5.htm#tagcjh_08_02_01_01 |
| 38 | package uuid |
| 39 | |
| 40 | import ( |
| 41 | "encoding/binary" |
| 42 | "encoding/hex" |
| 43 | "fmt" |
| 44 | "time" |
| 45 | ) |
| 46 | |
| 47 | // Size of a UUID in bytes. |
| 48 | const Size = 16 |
| 49 | |
| 50 | // UUID is an array type to represent the value of a UUID, as defined in RFC-9562. |
| 51 | type UUID [Size]byte |
| 52 | |
| 53 | // UUID versions. |
| 54 | const ( |
| 55 | _ byte = iota |
| 56 | V1 // Version 1 (date-time and MAC address) |
| 57 | _ // Version 2 (date-time and MAC address, DCE security version) [removed] |
| 58 | V3 // Version 3 (namespace name-based) |
| 59 | V4 // Version 4 (random) |
| 60 | V5 // Version 5 (namespace name-based) |
| 61 | V6 // Version 6 (k-sortable timestamp and random data, field-compatible with v1) |
| 62 | V7 // Version 7 (k-sortable timestamp and random data) |
| 63 | V8 // Version 8 (custom UUID implementations) |
| 64 | ) |
| 65 | |
| 66 | // UUID layout variants. |
| 67 | const ( |
| 68 | VariantNCS byte = iota |
| 69 | VariantRFC9562 |
| 70 | VariantMicrosoft |
| 71 | VariantFuture |
| 72 | ) |
| 73 | |
| 74 | // Backward-compatible variant for RFC 4122 |
| 75 | const VariantRFC4122 = VariantRFC9562 |
| 76 | |
| 77 | // UUID DCE domains. |
| 78 | const ( |
| 79 | DomainPerson = iota |
| 80 | DomainGroup |
| 81 | DomainOrg |
| 82 | ) |
| 83 | |
| 84 | // Timestamp is the count of 100-nanosecond intervals since 00:00:00.00, |
| 85 | // 15 October 1582 within a V1 or V6 UUID, or as a common intermediate |
| 86 | // representation of the (Unix Millisecond) timestamp within a V7 UUID. |
| 87 | // This type has no meaning for other UUID versions since they don't |
| 88 | // have an embedded timestamp. |
| 89 | type Timestamp uint64 |
| 90 | |
| 91 | const _100nsPerSecond = 10000000 |
| 92 | |
| 93 | // Time returns the time.Time representation of a Timestamp. |
| 94 | // |
| 95 | // The resulting time.Time: |
| 96 | // - Contains only wall clock time (no monotonic clock component) |
| 97 | // - Uses the local system timezone for the location |
| 98 | func (t Timestamp) Time() (time.Time, error) { |
| 99 | secs := uint64(t) / _100nsPerSecond |
| 100 | nsecs := 100 * (uint64(t) % _100nsPerSecond) |
| 101 | |
| 102 | return time.Unix(int64(secs)-(epochStart/_100nsPerSecond), int64(nsecs)), nil |
| 103 | } |
| 104 | |
| 105 | // TimestampFromV1 returns the Timestamp embedded within a V1 UUID. |
| 106 | // Returns an error if the UUID is any version other than 1. |
| 107 | func TimestampFromV1(u UUID) (Timestamp, error) { |
| 108 | if u.Version() != 1 { |
| 109 | err := fmt.Errorf("%w %s is version %d, not version 1", ErrInvalidVersion, u, u.Version()) |
| 110 | return 0, err |
| 111 | } |
| 112 | |
| 113 | low := binary.BigEndian.Uint32(u[0:4]) |
| 114 | mid := binary.BigEndian.Uint16(u[4:6]) |
| 115 | hi := binary.BigEndian.Uint16(u[6:8]) & 0xfff |
| 116 | |
| 117 | return Timestamp(uint64(low) + (uint64(mid) << 32) + (uint64(hi) << 48)), nil |
| 118 | } |
| 119 | |
| 120 | // TimestampFromV6 returns the Timestamp embedded within a V6 UUID. This |
| 121 | // function returns an error if the UUID is any version other than 6. |
| 122 | func TimestampFromV6(u UUID) (Timestamp, error) { |
| 123 | if u.Version() != 6 { |
| 124 | return 0, fmt.Errorf("%w %s is version %d, not version 6", ErrInvalidVersion, u, u.Version()) |
| 125 | } |
| 126 | |
| 127 | hi := binary.BigEndian.Uint32(u[0:4]) |
| 128 | mid := binary.BigEndian.Uint16(u[4:6]) |
| 129 | low := binary.BigEndian.Uint16(u[6:8]) & 0xfff |
| 130 | |
| 131 | return Timestamp(uint64(low) + (uint64(mid) << 12) + (uint64(hi) << 28)), nil |
| 132 | } |
| 133 | |
| 134 | // TimestampFromV7 returns the Timestamp embedded within a V7 UUID. This |
| 135 | // function returns an error if the UUID is any version other than 7. |
| 136 | func TimestampFromV7(u UUID) (Timestamp, error) { |
| 137 | if u.Version() != 7 { |
| 138 | return 0, fmt.Errorf("%w %s is version %d, not version 7", ErrInvalidVersion, u, u.Version()) |
| 139 | } |
| 140 | |
| 141 | t := 0 | |
| 142 | (int64(u[0]) << 40) | |
| 143 | (int64(u[1]) << 32) | |
| 144 | (int64(u[2]) << 24) | |
| 145 | (int64(u[3]) << 16) | |
| 146 | (int64(u[4]) << 8) | |
| 147 | int64(u[5]) |
| 148 | |
| 149 | // UUIDv7 stores MS since 1970-01-01 00:00:00, but the Timestamp |
| 150 | // type stores 100-nanosecond increments since 1582-10-15 00:00:00. |
| 151 | // This conversion multiplies ms by 10,000 to get 100-ns chunks and adds |
| 152 | // the difference between October 1582 and January 1970. |
| 153 | tsNanos := epochStart + (t * 10000) |
| 154 | return Timestamp(tsNanos), nil |
| 155 | } |
| 156 | |
| 157 | // Nil is the nil UUID, as specified in RFC-9562, that has all 128 bits set to |
| 158 | // zero. |
| 159 | var Nil = UUID{} |
| 160 | |
| 161 | // Max is the maximum UUID, as specified in RFC-9562, that has all 128 bits |
| 162 | // set to one. |
| 163 | var Max = UUID{ |
| 164 | 0xFF, |
| 165 | 0xFF, |
| 166 | 0xFF, |
| 167 | 0xFF, |
| 168 | 0xFF, |
| 169 | 0xFF, |
| 170 | 0xFF, |
| 171 | 0xFF, |
| 172 | 0xFF, |
| 173 | 0xFF, |
| 174 | 0xFF, |
| 175 | 0xFF, |
| 176 | 0xFF, |
| 177 | 0xFF, |
| 178 | 0xFF, |
| 179 | 0xFF, |
| 180 | } |
| 181 | |
| 182 | // Predefined namespace UUIDs. |
| 183 | var ( |
| 184 | NamespaceDNS = Must(FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8")) |
| 185 | NamespaceURL = Must(FromString("6ba7b811-9dad-11d1-80b4-00c04fd430c8")) |
| 186 | NamespaceOID = Must(FromString("6ba7b812-9dad-11d1-80b4-00c04fd430c8")) |
| 187 | NamespaceX500 = Must(FromString("6ba7b814-9dad-11d1-80b4-00c04fd430c8")) |
| 188 | ) |
| 189 | |
| 190 | // IsNil returns if the UUID is equal to the nil UUID |
| 191 | func (u UUID) IsNil() bool { |
| 192 | return u == Nil |
| 193 | } |
| 194 | |
| 195 | // IsZero returns if the UUID is equal to the zero UUID (same as IsNil). |
| 196 | // This method is provided to satisfy the bsoncodec.Zeroer interface for MongoDB |
| 197 | // omitzero tag support. See: https://github.com/gofrs/uuid/issues/224 |
| 198 | func (u UUID) IsZero() bool { |
| 199 | return u == Nil |
| 200 | } |
| 201 | |
| 202 | // Version returns the algorithm version used to generate the UUID. |
| 203 | func (u UUID) Version() byte { |
| 204 | return u[6] >> 4 |
| 205 | } |
| 206 | |
| 207 | // Variant returns the UUID layout variant. |
| 208 | func (u UUID) Variant() byte { |
| 209 | switch { |
| 210 | case (u[8] >> 7) == 0x00: |
| 211 | return VariantNCS |
| 212 | case (u[8] >> 6) == 0x02: |
| 213 | return VariantRFC9562 |
| 214 | case (u[8] >> 5) == 0x06: |
| 215 | return VariantMicrosoft |
| 216 | case (u[8] >> 5) == 0x07: |
| 217 | fallthrough |
| 218 | default: |
| 219 | return VariantFuture |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | // Bytes returns a byte slice representation of the UUID. |
| 224 | func (u UUID) Bytes() []byte { |
| 225 | return u[:] |
| 226 | } |
| 227 | |
| 228 | // encodeCanonical encodes the canonical RFC-9562 form of UUID u into the |
| 229 | // first 36 bytes dst. |
| 230 | func encodeCanonical(dst []byte, u UUID) { |
| 231 | const hextable = "0123456789abcdef" |
| 232 | dst[8] = '-' |
| 233 | dst[13] = '-' |
| 234 | dst[18] = '-' |
| 235 | dst[23] = '-' |
| 236 | for i, x := range [16]byte{ |
| 237 | 0, 2, 4, 6, |
| 238 | 9, 11, |
| 239 | 14, 16, |
| 240 | 19, 21, |
| 241 | 24, 26, 28, 30, 32, 34, |
| 242 | } { |
| 243 | c := u[i] |
| 244 | dst[x] = hextable[c>>4] |
| 245 | dst[x+1] = hextable[c&0x0f] |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | // String returns a canonical RFC-9562 string representation of the UUID: |
| 250 | // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx. |
| 251 | func (u UUID) String() string { |
| 252 | var buf [36]byte |
| 253 | encodeCanonical(buf[:], u) |
| 254 | return string(buf[:]) |
| 255 | } |
| 256 | |
| 257 | // Format implements fmt.Formatter for UUID values. |
| 258 | // |
| 259 | // The behavior is as follows: |
| 260 | // The 'x' and 'X' verbs output only the hex digits of the UUID, using a-f for 'x' and A-F for 'X'. |
| 261 | // The 'v', '+v', 's' and 'q' verbs return the canonical RFC-9562 string representation. |
| 262 | // The 'S' verb returns the RFC-9562 format, but with capital hex digits. |
| 263 | // The '#v' verb returns the "Go syntax" representation, which is a 16 byte array initializer. |
| 264 | // All other verbs not handled directly by the fmt package (like '%p') are unsupported and will return |
| 265 | // "%!verb(uuid.UUID=value)" as recommended by the fmt package. |
| 266 | func (u UUID) Format(f fmt.State, c rune) { |
| 267 | if c == 'v' && f.Flag('#') { |
| 268 | fmt.Fprintf(f, "%#v", [Size]byte(u)) |
| 269 | return |
| 270 | } |
| 271 | switch c { |
| 272 | case 'x', 'X': |
| 273 | b := make([]byte, 32) |
| 274 | hex.Encode(b, u[:]) |
| 275 | if c == 'X' { |
| 276 | toUpperHex(b) |
| 277 | } |
| 278 | _, _ = f.Write(b) |
| 279 | case 'v', 's', 'S': |
| 280 | b, _ := u.MarshalText() |
| 281 | if c == 'S' { |
| 282 | toUpperHex(b) |
| 283 | } |
| 284 | _, _ = f.Write(b) |
| 285 | case 'q': |
| 286 | b := make([]byte, 38) |
| 287 | b[0] = '"' |
| 288 | encodeCanonical(b[1:], u) |
| 289 | b[37] = '"' |
| 290 | _, _ = f.Write(b) |
| 291 | default: |
| 292 | // invalid/unsupported format verb |
| 293 | fmt.Fprintf(f, "%%!%c(uuid.UUID=%s)", c, u.String()) |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | func toUpperHex(b []byte) { |
| 298 | for i, c := range b { |
| 299 | if 'a' <= c && c <= 'f' { |
| 300 | b[i] = c - ('a' - 'A') |
| 301 | } |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | // SetVersion sets the version bits. |
| 306 | func (u *UUID) SetVersion(v byte) { |
| 307 | u[6] = (u[6] & 0x0f) | (v << 4) |
| 308 | } |
| 309 | |
| 310 | // SetVariant sets the variant bits. |
| 311 | func (u *UUID) SetVariant(v byte) { |
| 312 | switch v { |
| 313 | case VariantNCS: |
| 314 | u[8] = (u[8]&(0xff>>1) | (0x00 << 7)) |
| 315 | case VariantRFC9562: |
| 316 | u[8] = (u[8]&(0xff>>2) | (0x02 << 6)) |
| 317 | case VariantMicrosoft: |
| 318 | u[8] = (u[8]&(0xff>>3) | (0x06 << 5)) |
| 319 | case VariantFuture: |
| 320 | fallthrough |
| 321 | default: |
| 322 | u[8] = (u[8]&(0xff>>3) | (0x07 << 5)) |
| 323 | } |
| 324 | } |
| 325 | |
| 326 | // Must is a helper that wraps a call to a function returning (UUID, error) |
| 327 | // and panics if the error is non-nil. It is intended for use in variable |
| 328 | // initializations such as |
| 329 | // |
| 330 | // var packageUUID = uuid.Must(uuid.FromString("123e4567-e89b-12d3-a456-426655440000")) |
| 331 | func Must(u UUID, err error) UUID { |
| 332 | if err != nil { |
| 333 | panic(err) |
| 334 | } |
| 335 | return u |
| 336 | } |