Path: blob/main/vendor/github.com/google/uuid/version4.go
2875 views
// Copyright 2016 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 "io"78// New creates a new random UUID or panics. New is equivalent to9// the expression10//11// uuid.Must(uuid.NewRandom())12func New() UUID {13return Must(NewRandom())14}1516// NewString creates a new random UUID and returns it as a string or panics.17// NewString is equivalent to the expression18//19// uuid.New().String()20func NewString() string {21return Must(NewRandom()).String()22}2324// NewRandom returns a Random (Version 4) UUID.25//26// The strength of the UUIDs is based on the strength of the crypto/rand27// package.28//29// Uses the randomness pool if it was enabled with EnableRandPool.30//31// A note about uniqueness derived from the UUID Wikipedia entry:32//33// Randomly generated UUIDs have 122 random bits. One's annual risk of being34// hit by a meteorite is estimated to be one chance in 17 billion, that35// means the probability is about 0.00000000006 (6 × 10−11),36// equivalent to the odds of creating a few tens of trillions of UUIDs in a37// year and having one duplicate.38func NewRandom() (UUID, error) {39if !poolEnabled {40return NewRandomFromReader(rander)41}42return newRandomFromPool()43}4445// NewRandomFromReader returns a UUID based on bytes read from a given io.Reader.46func NewRandomFromReader(r io.Reader) (UUID, error) {47var uuid UUID48_, err := io.ReadFull(r, uuid[:])49if err != nil {50return Nil, err51}52uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 453uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 1054return uuid, nil55}5657func newRandomFromPool() (UUID, error) {58var uuid UUID59poolMu.Lock()60if poolPos == randPoolSize {61_, err := io.ReadFull(rander, pool[:])62if err != nil {63poolMu.Unlock()64return Nil, err65}66poolPos = 067}68copy(uuid[:], pool[poolPos:(poolPos+16)])69poolPos += 1670poolMu.Unlock()7172uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 473uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 1074return uuid, nil75}767778