version4.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // 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. package uuid
  5. import "io"
  6. // New creates a new random UUID or panics. New is equivalent to
  7. // the expression
  8. //
  9. // uuid.Must(uuid.NewRandom())
  10. func New() UUID {
  11. return Must(NewRandom())
  12. }
  13. // NewRandom returns a Random (Version 4) UUID.
  14. //
  15. // The strength of the UUIDs is based on the strength of the crypto/rand
  16. // package.
  17. //
  18. // A note about uniqueness derived from the UUID Wikipedia entry:
  19. //
  20. // Randomly generated UUIDs have 122 random bits. One's annual risk of being
  21. // hit by a meteorite is estimated to be one chance in 17 billion, that
  22. // means the probability is about 0.00000000006 (6 × 10−11),
  23. // equivalent to the odds of creating a few tens of trillions of UUIDs in a
  24. // year and having one duplicate.
  25. func NewRandom() (UUID, error) {
  26. return NewRandomFromReader(rander)
  27. }
  28. // NewRandomFromReader returns a UUID based on bytes read from a given io.Reader.
  29. func NewRandomFromReader(r io.Reader) (UUID, error) {
  30. var uuid UUID
  31. _, err := io.ReadFull(r, 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. }