blob: 84af91c9f54f08c4d707077a8ab8d5eaf2ffa546 [file] [log] [blame]
Takahiro Suzuki241c10e2020-12-17 20:17:57 +09001// 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// NewRandom returns a Random (Version 4) UUID.
18//
19// The strength of the UUIDs is based on the strength of the crypto/rand
20// package.
21//
22// A note about uniqueness derived from the UUID Wikipedia entry:
23//
24// Randomly generated UUIDs have 122 random bits. One's annual risk of being
25// hit by a meteorite is estimated to be one chance in 17 billion, that
26// means the probability is about 0.00000000006 (6 × 10−11),
27// equivalent to the odds of creating a few tens of trillions of UUIDs in a
28// year and having one duplicate.
29func NewRandom() (UUID, error) {
30 var uuid UUID
31 _, err := io.ReadFull(rander, uuid[:])
32 if err != nil {
33 return Nil, err
34 }
35 uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4
36 uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10
37 return uuid, nil
38}