version1.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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 (
  6. "encoding/binary"
  7. )
  8. // NewUUID returns a Version 1 UUID based on the current NodeID and clock
  9. // sequence, and the current time. If the NodeID has not been set by SetNodeID
  10. // or SetNodeInterface then it will be set automatically. If the NodeID cannot
  11. // be set NewUUID returns nil. If clock sequence has not been set by
  12. // SetClockSequence then it will be set automatically. If GetTime fails to
  13. // return the current NewUUID returns nil and an error.
  14. //
  15. // In most cases, New should be used.
  16. func NewUUID() (UUID, error) {
  17. nodeMu.Lock()
  18. if nodeID == zeroID {
  19. setNodeInterface("")
  20. }
  21. nodeMu.Unlock()
  22. var uuid UUID
  23. now, seq, err := GetTime()
  24. if err != nil {
  25. return uuid, err
  26. }
  27. timeLow := uint32(now & 0xffffffff)
  28. timeMid := uint16((now >> 32) & 0xffff)
  29. timeHi := uint16((now >> 48) & 0x0fff)
  30. timeHi |= 0x1000 // Version 1
  31. binary.BigEndian.PutUint32(uuid[0:], timeLow)
  32. binary.BigEndian.PutUint16(uuid[4:], timeMid)
  33. binary.BigEndian.PutUint16(uuid[6:], timeHi)
  34. binary.BigEndian.PutUint16(uuid[8:], seq)
  35. copy(uuid[10:], nodeID[:])
  36. return uuid, nil
  37. }