Path: blob/main/vendor/github.com/google/uuid/uuid.go
2875 views
// Copyright 2018 Google Inc. All rights reserved.1// Use of this source code is governed by a BSD-style2// license that can be found in the LICENSE file.34package uuid56import (7"bytes"8"crypto/rand"9"encoding/hex"10"errors"11"fmt"12"io"13"strings"14"sync"15)1617// A UUID is a 128 bit (16 byte) Universal Unique IDentifier as defined in RFC18// 4122.19type UUID [16]byte2021// A Version represents a UUID's version.22type Version byte2324// A Variant represents a UUID's variant.25type Variant byte2627// Constants returned by Variant.28const (29Invalid = Variant(iota) // Invalid UUID30RFC4122 // The variant specified in RFC412231Reserved // Reserved, NCS backward compatibility.32Microsoft // Reserved, Microsoft Corporation backward compatibility.33Future // Reserved for future definition.34)3536const randPoolSize = 16 * 163738var (39rander = rand.Reader // random function40poolEnabled = false41poolMu sync.Mutex42poolPos = randPoolSize // protected with poolMu43pool [randPoolSize]byte // protected with poolMu44)4546type invalidLengthError struct{ len int }4748func (err invalidLengthError) Error() string {49return fmt.Sprintf("invalid UUID length: %d", err.len)50}5152// IsInvalidLengthError is matcher function for custom error invalidLengthError53func IsInvalidLengthError(err error) bool {54_, ok := err.(invalidLengthError)55return ok56}5758// Parse decodes s into a UUID or returns an error if it cannot be parsed. Both59// the standard UUID forms defined in RFC 412260// (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and61// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) are decoded. In addition,62// Parse accepts non-standard strings such as the raw hex encoding63// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx and 38 byte "Microsoft style" encodings,64// e.g. {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}. Only the middle 36 bytes are65// examined in the latter case. Parse should not be used to validate strings as66// it parses non-standard encodings as indicated above.67func Parse(s string) (UUID, error) {68var uuid UUID69switch len(s) {70// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx71case 36:7273// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx74case 36 + 9:75if !strings.EqualFold(s[:9], "urn:uuid:") {76return uuid, fmt.Errorf("invalid urn prefix: %q", s[:9])77}78s = s[9:]7980// {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}81case 36 + 2:82s = s[1:]8384// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx85case 32:86var ok bool87for i := range uuid {88uuid[i], ok = xtob(s[i*2], s[i*2+1])89if !ok {90return uuid, errors.New("invalid UUID format")91}92}93return uuid, nil94default:95return uuid, invalidLengthError{len(s)}96}97// s is now at least 36 bytes long98// it must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx99if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' {100return uuid, errors.New("invalid UUID format")101}102for i, x := range [16]int{1030, 2, 4, 6,1049, 11,10514, 16,10619, 21,10724, 26, 28, 30, 32, 34,108} {109v, ok := xtob(s[x], s[x+1])110if !ok {111return uuid, errors.New("invalid UUID format")112}113uuid[i] = v114}115return uuid, nil116}117118// ParseBytes is like Parse, except it parses a byte slice instead of a string.119func ParseBytes(b []byte) (UUID, error) {120var uuid UUID121switch len(b) {122case 36: // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx123case 36 + 9: // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx124if !bytes.EqualFold(b[:9], []byte("urn:uuid:")) {125return uuid, fmt.Errorf("invalid urn prefix: %q", b[:9])126}127b = b[9:]128case 36 + 2: // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}129b = b[1:]130case 32: // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx131var ok bool132for i := 0; i < 32; i += 2 {133uuid[i/2], ok = xtob(b[i], b[i+1])134if !ok {135return uuid, errors.New("invalid UUID format")136}137}138return uuid, nil139default:140return uuid, invalidLengthError{len(b)}141}142// s is now at least 36 bytes long143// it must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx144if b[8] != '-' || b[13] != '-' || b[18] != '-' || b[23] != '-' {145return uuid, errors.New("invalid UUID format")146}147for i, x := range [16]int{1480, 2, 4, 6,1499, 11,15014, 16,15119, 21,15224, 26, 28, 30, 32, 34,153} {154v, ok := xtob(b[x], b[x+1])155if !ok {156return uuid, errors.New("invalid UUID format")157}158uuid[i] = v159}160return uuid, nil161}162163// MustParse is like Parse but panics if the string cannot be parsed.164// It simplifies safe initialization of global variables holding compiled UUIDs.165func MustParse(s string) UUID {166uuid, err := Parse(s)167if err != nil {168panic(`uuid: Parse(` + s + `): ` + err.Error())169}170return uuid171}172173// FromBytes creates a new UUID from a byte slice. Returns an error if the slice174// does not have a length of 16. The bytes are copied from the slice.175func FromBytes(b []byte) (uuid UUID, err error) {176err = uuid.UnmarshalBinary(b)177return uuid, err178}179180// Must returns uuid if err is nil and panics otherwise.181func Must(uuid UUID, err error) UUID {182if err != nil {183panic(err)184}185return uuid186}187188// Validate returns an error if s is not a properly formatted UUID in one of the following formats:189// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx190// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx191// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx192// {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}193// It returns an error if the format is invalid, otherwise nil.194func Validate(s string) error {195switch len(s) {196// Standard UUID format197case 36:198199// UUID with "urn:uuid:" prefix200case 36 + 9:201if !strings.EqualFold(s[:9], "urn:uuid:") {202return fmt.Errorf("invalid urn prefix: %q", s[:9])203}204s = s[9:]205206// UUID enclosed in braces207case 36 + 2:208if s[0] != '{' || s[len(s)-1] != '}' {209return fmt.Errorf("invalid bracketed UUID format")210}211s = s[1 : len(s)-1]212213// UUID without hyphens214case 32:215for i := 0; i < len(s); i += 2 {216_, ok := xtob(s[i], s[i+1])217if !ok {218return errors.New("invalid UUID format")219}220}221222default:223return invalidLengthError{len(s)}224}225226// Check for standard UUID format227if len(s) == 36 {228if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' {229return errors.New("invalid UUID format")230}231for _, x := range []int{0, 2, 4, 6, 9, 11, 14, 16, 19, 21, 24, 26, 28, 30, 32, 34} {232if _, ok := xtob(s[x], s[x+1]); !ok {233return errors.New("invalid UUID format")234}235}236}237238return nil239}240241// String returns the string form of uuid, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx242// , or "" if uuid is invalid.243func (uuid UUID) String() string {244var buf [36]byte245encodeHex(buf[:], uuid)246return string(buf[:])247}248249// URN returns the RFC 2141 URN form of uuid,250// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, or "" if uuid is invalid.251func (uuid UUID) URN() string {252var buf [36 + 9]byte253copy(buf[:], "urn:uuid:")254encodeHex(buf[9:], uuid)255return string(buf[:])256}257258func encodeHex(dst []byte, uuid UUID) {259hex.Encode(dst, uuid[:4])260dst[8] = '-'261hex.Encode(dst[9:13], uuid[4:6])262dst[13] = '-'263hex.Encode(dst[14:18], uuid[6:8])264dst[18] = '-'265hex.Encode(dst[19:23], uuid[8:10])266dst[23] = '-'267hex.Encode(dst[24:], uuid[10:])268}269270// Variant returns the variant encoded in uuid.271func (uuid UUID) Variant() Variant {272switch {273case (uuid[8] & 0xc0) == 0x80:274return RFC4122275case (uuid[8] & 0xe0) == 0xc0:276return Microsoft277case (uuid[8] & 0xe0) == 0xe0:278return Future279default:280return Reserved281}282}283284// Version returns the version of uuid.285func (uuid UUID) Version() Version {286return Version(uuid[6] >> 4)287}288289func (v Version) String() string {290if v > 15 {291return fmt.Sprintf("BAD_VERSION_%d", v)292}293return fmt.Sprintf("VERSION_%d", v)294}295296func (v Variant) String() string {297switch v {298case RFC4122:299return "RFC4122"300case Reserved:301return "Reserved"302case Microsoft:303return "Microsoft"304case Future:305return "Future"306case Invalid:307return "Invalid"308}309return fmt.Sprintf("BadVariant%d", int(v))310}311312// SetRand sets the random number generator to r, which implements io.Reader.313// If r.Read returns an error when the package requests random data then314// a panic will be issued.315//316// Calling SetRand with nil sets the random number generator to the default317// generator.318func SetRand(r io.Reader) {319if r == nil {320rander = rand.Reader321return322}323rander = r324}325326// EnableRandPool enables internal randomness pool used for Random327// (Version 4) UUID generation. The pool contains random bytes read from328// the random number generator on demand in batches. Enabling the pool329// may improve the UUID generation throughput significantly.330//331// Since the pool is stored on the Go heap, this feature may be a bad fit332// for security sensitive applications.333//334// Both EnableRandPool and DisableRandPool are not thread-safe and should335// only be called when there is no possibility that New or any other336// UUID Version 4 generation function will be called concurrently.337func EnableRandPool() {338poolEnabled = true339}340341// DisableRandPool disables the randomness pool if it was previously342// enabled with EnableRandPool.343//344// Both EnableRandPool and DisableRandPool are not thread-safe and should345// only be called when there is no possibility that New or any other346// UUID Version 4 generation function will be called concurrently.347func DisableRandPool() {348poolEnabled = false349defer poolMu.Unlock()350poolMu.Lock()351poolPos = randPoolSize352}353354// UUIDs is a slice of UUID types.355type UUIDs []UUID356357// Strings returns a string slice containing the string form of each UUID in uuids.358func (uuids UUIDs) Strings() []string {359var uuidStrs = make([]string, len(uuids))360for i, uuid := range uuids {361uuidStrs[i] = uuid.String()362}363return uuidStrs364}365366367