uuid.go raw

   1  // Copyright (C) 2013-2018 by Maxim Bublis <b@codemonkey.ru>
   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-4122 and the Peabody RFC Draft (revision 03).
  24  //
  25  // RFC-4122[1] provides the specification for versions 1, 3, 4, and 5. The
  26  // Peabody UUID RFC Draft[2] provides the specification for the new k-sortable
  27  // UUIDs, versions 6 and 7.
  28  //
  29  // DCE 1.1[3] provides the specification for version 2, but version 2 support
  30  // was removed from this package in v4 due to some concerns with the
  31  // specification itself. Reading the spec, it seems that it would result in
  32  // generating UUIDs that aren't very unique. In having read the spec it seemed
  33  // that our implementation did not meet the spec. It also seems to be at-odds
  34  // with RFC 4122, meaning we would need quite a bit of special code to support
  35  // it. Lastly, there were no Version 2 implementations that we could find to
  36  // ensure we were understanding the specification correctly.
  37  //
  38  // [1] https://tools.ietf.org/html/rfc4122
  39  // [2] https://datatracker.ietf.org/doc/html/draft-peabody-dispatch-new-uuid-format-03
  40  // [3] http://pubs.opengroup.org/onlinepubs/9696989899/chap5.htm#tagcjh_08_02_01_01
  41  package uuid
  42  
  43  import (
  44  	"encoding/binary"
  45  	"encoding/hex"
  46  	"fmt"
  47  	"time"
  48  )
  49  
  50  // Size of a UUID in bytes.
  51  const Size = 16
  52  
  53  // UUID is an array type to represent the value of a UUID, as defined in RFC-4122.
  54  type UUID [Size]byte
  55  
  56  // UUID versions.
  57  const (
  58  	_  byte = iota
  59  	V1      // Version 1 (date-time and MAC address)
  60  	_       // Version 2 (date-time and MAC address, DCE security version) [removed]
  61  	V3      // Version 3 (namespace name-based)
  62  	V4      // Version 4 (random)
  63  	V5      // Version 5 (namespace name-based)
  64  	V6      // Version 6 (k-sortable timestamp and random data, field-compatible with v1) [peabody draft]
  65  	V7      // Version 7 (k-sortable timestamp and random data) [peabody draft]
  66  	_       // Version 8 (k-sortable timestamp, meant for custom implementations) [peabody draft] [not implemented]
  67  )
  68  
  69  // UUID layout variants.
  70  const (
  71  	VariantNCS byte = iota
  72  	VariantRFC4122
  73  	VariantMicrosoft
  74  	VariantFuture
  75  )
  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 UUID. This type has no meaning for other
  86  // UUID versions since they don't have an embedded timestamp.
  87  type Timestamp uint64
  88  
  89  const _100nsPerSecond = 10000000
  90  
  91  // Time returns the UTC time.Time representation of a Timestamp
  92  func (t Timestamp) Time() (time.Time, error) {
  93  	secs := uint64(t) / _100nsPerSecond
  94  	nsecs := 100 * (uint64(t) % _100nsPerSecond)
  95  
  96  	return time.Unix(int64(secs)-(epochStart/_100nsPerSecond), int64(nsecs)), nil
  97  }
  98  
  99  // TimestampFromV1 returns the Timestamp embedded within a V1 UUID.
 100  // Returns an error if the UUID is any version other than 1.
 101  func TimestampFromV1(u UUID) (Timestamp, error) {
 102  	if u.Version() != 1 {
 103  		err := fmt.Errorf("uuid: %s is version %d, not version 1", u, u.Version())
 104  		return 0, err
 105  	}
 106  
 107  	low := binary.BigEndian.Uint32(u[0:4])
 108  	mid := binary.BigEndian.Uint16(u[4:6])
 109  	hi := binary.BigEndian.Uint16(u[6:8]) & 0xfff
 110  
 111  	return Timestamp(uint64(low) + (uint64(mid) << 32) + (uint64(hi) << 48)), nil
 112  }
 113  
 114  // TimestampFromV6 returns the Timestamp embedded within a V6 UUID. This
 115  // function returns an error if the UUID is any version other than 6.
 116  //
 117  // This is implemented based on revision 03 of the Peabody UUID draft, and may
 118  // be subject to change pending further revisions. Until the final specification
 119  // revision is finished, changes required to implement updates to the spec will
 120  // not be considered a breaking change. They will happen as a minor version
 121  // releases until the spec is final.
 122  func TimestampFromV6(u UUID) (Timestamp, error) {
 123  	if u.Version() != 6 {
 124  		return 0, fmt.Errorf("uuid: %s is version %d, not version 6", 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  // Nil is the nil UUID, as specified in RFC-4122, that has all 128 bits set to
 135  // zero.
 136  var Nil = UUID{}
 137  
 138  // Predefined namespace UUIDs.
 139  var (
 140  	NamespaceDNS  = Must(FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8"))
 141  	NamespaceURL  = Must(FromString("6ba7b811-9dad-11d1-80b4-00c04fd430c8"))
 142  	NamespaceOID  = Must(FromString("6ba7b812-9dad-11d1-80b4-00c04fd430c8"))
 143  	NamespaceX500 = Must(FromString("6ba7b814-9dad-11d1-80b4-00c04fd430c8"))
 144  )
 145  
 146  // IsNil returns if the UUID is equal to the nil UUID
 147  func (u UUID) IsNil() bool {
 148  	return u == Nil
 149  }
 150  
 151  // Version returns the algorithm version used to generate the UUID.
 152  func (u UUID) Version() byte {
 153  	return u[6] >> 4
 154  }
 155  
 156  // Variant returns the UUID layout variant.
 157  func (u UUID) Variant() byte {
 158  	switch {
 159  	case (u[8] >> 7) == 0x00:
 160  		return VariantNCS
 161  	case (u[8] >> 6) == 0x02:
 162  		return VariantRFC4122
 163  	case (u[8] >> 5) == 0x06:
 164  		return VariantMicrosoft
 165  	case (u[8] >> 5) == 0x07:
 166  		fallthrough
 167  	default:
 168  		return VariantFuture
 169  	}
 170  }
 171  
 172  // Bytes returns a byte slice representation of the UUID.
 173  func (u UUID) Bytes() []byte {
 174  	return u[:]
 175  }
 176  
 177  // encodeCanonical encodes the canonical RFC-4122 form of UUID u into the
 178  // first 36 bytes dst.
 179  func encodeCanonical(dst []byte, u UUID) {
 180  	const hextable = "0123456789abcdef"
 181  	dst[8] = '-'
 182  	dst[13] = '-'
 183  	dst[18] = '-'
 184  	dst[23] = '-'
 185  	for i, x := range [16]byte{
 186  		0, 2, 4, 6,
 187  		9, 11,
 188  		14, 16,
 189  		19, 21,
 190  		24, 26, 28, 30, 32, 34,
 191  	} {
 192  		c := u[i]
 193  		dst[x] = hextable[c>>4]
 194  		dst[x+1] = hextable[c&0x0f]
 195  	}
 196  }
 197  
 198  // String returns a canonical RFC-4122 string representation of the UUID:
 199  // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
 200  func (u UUID) String() string {
 201  	var buf [36]byte
 202  	encodeCanonical(buf[:], u)
 203  	return string(buf[:])
 204  }
 205  
 206  // Format implements fmt.Formatter for UUID values.
 207  //
 208  // The behavior is as follows:
 209  // The 'x' and 'X' verbs output only the hex digits of the UUID, using a-f for 'x' and A-F for 'X'.
 210  // The 'v', '+v', 's' and 'q' verbs return the canonical RFC-4122 string representation.
 211  // The 'S' verb returns the RFC-4122 format, but with capital hex digits.
 212  // The '#v' verb returns the "Go syntax" representation, which is a 16 byte array initializer.
 213  // All other verbs not handled directly by the fmt package (like '%p') are unsupported and will return
 214  // "%!verb(uuid.UUID=value)" as recommended by the fmt package.
 215  func (u UUID) Format(f fmt.State, c rune) {
 216  	if c == 'v' && f.Flag('#') {
 217  		fmt.Fprintf(f, "%#v", [Size]byte(u))
 218  		return
 219  	}
 220  	switch c {
 221  	case 'x', 'X':
 222  		b := make([]byte, 32)
 223  		hex.Encode(b, u[:])
 224  		if c == 'X' {
 225  			toUpperHex(b)
 226  		}
 227  		_, _ = f.Write(b)
 228  	case 'v', 's', 'S':
 229  		b, _ := u.MarshalText()
 230  		if c == 'S' {
 231  			toUpperHex(b)
 232  		}
 233  		_, _ = f.Write(b)
 234  	case 'q':
 235  		b := make([]byte, 38)
 236  		b[0] = '"'
 237  		encodeCanonical(b[1:], u)
 238  		b[37] = '"'
 239  		_, _ = f.Write(b)
 240  	default:
 241  		// invalid/unsupported format verb
 242  		fmt.Fprintf(f, "%%!%c(uuid.UUID=%s)", c, u.String())
 243  	}
 244  }
 245  
 246  func toUpperHex(b []byte) {
 247  	for i, c := range b {
 248  		if 'a' <= c && c <= 'f' {
 249  			b[i] = c - ('a' - 'A')
 250  		}
 251  	}
 252  }
 253  
 254  // SetVersion sets the version bits.
 255  func (u *UUID) SetVersion(v byte) {
 256  	u[6] = (u[6] & 0x0f) | (v << 4)
 257  }
 258  
 259  // SetVariant sets the variant bits.
 260  func (u *UUID) SetVariant(v byte) {
 261  	switch v {
 262  	case VariantNCS:
 263  		u[8] = (u[8]&(0xff>>1) | (0x00 << 7))
 264  	case VariantRFC4122:
 265  		u[8] = (u[8]&(0xff>>2) | (0x02 << 6))
 266  	case VariantMicrosoft:
 267  		u[8] = (u[8]&(0xff>>3) | (0x06 << 5))
 268  	case VariantFuture:
 269  		fallthrough
 270  	default:
 271  		u[8] = (u[8]&(0xff>>3) | (0x07 << 5))
 272  	}
 273  }
 274  
 275  // Must is a helper that wraps a call to a function returning (UUID, error)
 276  // and panics if the error is non-nil. It is intended for use in variable
 277  // initializations such as
 278  //
 279  //	var packageUUID = uuid.Must(uuid.FromString("123e4567-e89b-12d3-a456-426655440000"))
 280  func Must(u UUID, err error) UUID {
 281  	if err != nil {
 282  		panic(err)
 283  	}
 284  	return u
 285  }
 286