github.com/mdaxf/iac@v0.0.0-20240519030858-58a061660378/vendor_skip/go.mongodb.org/mongo-driver/internal/uuid/uuid.go (about) 1 // Copyright (C) MongoDB, Inc. 2017-present. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 // not use this file except in compliance with the License. You may obtain 5 // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 7 package uuid 8 9 import ( 10 "encoding/hex" 11 "io" 12 13 "go.mongodb.org/mongo-driver/internal/randutil" 14 ) 15 16 // UUID represents a UUID. 17 type UUID [16]byte 18 19 // A source is a UUID generator that reads random values from a io.Reader. 20 // It should be safe to use from multiple goroutines. 21 type source struct { 22 random io.Reader 23 } 24 25 // new returns a random UUIDv4 with bytes read from the source's random number generator. 26 func (s *source) new() (UUID, error) { 27 var uuid UUID 28 _, err := io.ReadFull(s.random, uuid[:]) 29 if err != nil { 30 return UUID{}, err 31 } 32 uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4 33 uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10 34 return uuid, nil 35 } 36 37 // newSource returns a source that uses a pseudo-random number generator in reandutil package. 38 // It is intended to be used to initialize the package-global UUID generator. 39 func newSource() *source { 40 return &source{ 41 random: randutil.NewLockedRand(), 42 } 43 } 44 45 // globalSource is a package-global pseudo-random UUID generator. 46 var globalSource = newSource() 47 48 // New returns a random UUIDv4. It uses a global pseudo-random number generator in randutil 49 // at package initialization. 50 // 51 // New should not be used to generate cryptographically-secure random UUIDs. 52 func New() (UUID, error) { 53 return globalSource.new() 54 } 55 56 func (uuid UUID) String() string { 57 var str [36]byte 58 hex.Encode(str[:], uuid[:4]) 59 str[8] = '-' 60 hex.Encode(str[9:13], uuid[4:6]) 61 str[13] = '-' 62 hex.Encode(str[14:18], uuid[6:8]) 63 str[18] = '-' 64 hex.Encode(str[19:23], uuid[8:10]) 65 str[23] = '-' 66 hex.Encode(str[24:], uuid[10:]) 67 return string(str[:]) 68 }