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. var uuid UUID
  18. now, seq, err := GetTime()
  19. if err != nil {
  20. return uuid, err
  21. }
  22. timeLow := uint32(now & 0xffffffff)
  23. timeMid := uint16((now >> 32) & 0xffff)
  24. timeHi := uint16((now >> 48) & 0x0fff)
  25. timeHi |= 0x1000 // Version 1
  26. binary.BigEndian.PutUint32(uuid[0:], timeLow)
  27. binary.BigEndian.PutUint16(uuid[4:], timeMid)
  28. binary.BigEndian.PutUint16(uuid[6:], timeHi)
  29. binary.BigEndian.PutUint16(uuid[8:], seq)
  30. nodeMu.Lock()
  31. if nodeID == zeroID {
  32. setNodeInterface("")
  33. }
  34. copy(uuid[10:], nodeID[:])
  35. nodeMu.Unlock()
  36. return uuid, nil
  37. }