blob: 86160fbd0725f3f63b56daaf757323c0d4749588 [file] [log] [blame]
Prince Pereirac1c21d62021-04-22 08:38:15 +00001// Copyright 2016 Google Inc. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package uuid
6
7import "io"
8
9// New creates a new random UUID or panics. New is equivalent to
10// the expression
11//
12// uuid.Must(uuid.NewRandom())
13func New() UUID {
14 return Must(NewRandom())
15}
16
17// NewString creates a new random UUID and returns it as a string or panics.
18// NewString is equivalent to the expression
19//
20// uuid.New().String()
21func NewString() string {
22 return Must(NewRandom()).String()
23}
24
25// NewRandom returns a Random (Version 4) UUID.
26//
27// The strength of the UUIDs is based on the strength of the crypto/rand
28// package.
29//
30// A note about uniqueness derived from the UUID Wikipedia entry:
31//
32// Randomly generated UUIDs have 122 random bits. One's annual risk of being
33// hit by a meteorite is estimated to be one chance in 17 billion, that
34// means the probability is about 0.00000000006 (6 × 10−11),
35// equivalent to the odds of creating a few tens of trillions of UUIDs in a
36// year and having one duplicate.
37func NewRandom() (UUID, error) {
38 return NewRandomFromReader(rander)
39}
40
41// NewRandomFromReader returns a UUID based on bytes read from a given io.Reader.
42func NewRandomFromReader(r io.Reader) (UUID, error) {
43 var uuid UUID
44 _, err := io.ReadFull(r, uuid[:])
45 if err != nil {
46 return Nil, err
47 }
48 uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4
49 uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10
50 return uuid, nil
51}