blob: c110465db5900d8715cd2d65c06cad506aeeb7aa [file] [log] [blame]
amit.ghosh258d14c2020-10-02 15:13:38 +02001// 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 return NewRandomFromReader(rander)
31}
32
33// NewRandomFromReader returns a UUID based on bytes read from a given io.Reader.
34func NewRandomFromReader(r io.Reader) (UUID, error) {
35 var uuid UUID
36 _, err := io.ReadFull(r, uuid[:])
37 if err != nil {
38 return Nil, err
39 }
40 uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4
41 uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10
42 return uuid, nil
43}