You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

version4.go 1.1KB

1234567891011121314151617181920212223242526272829303132333435363738
  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. var uuid UUID
  27. _, err := io.ReadFull(rander, uuid[:])
  28. if err != nil {
  29. return Nil, err
  30. }
  31. uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4
  32. uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10
  33. return uuid, nil
  34. }