version1.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // Copyright 2011 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.
  14. func NewUUID() UUID {
  15. if nodeID == nil {
  16. SetNodeInterface("")
  17. }
  18. now, err := GetTime()
  19. if err != nil {
  20. return nil
  21. }
  22. uuid := make([]byte, 16)
  23. time_low := uint32(now & 0xffffffff)
  24. time_mid := uint16((now >> 32) & 0xffff)
  25. time_hi := uint16((now >> 48) & 0x0fff)
  26. time_hi |= 0x1000 // Version 1
  27. binary.BigEndian.PutUint32(uuid[0:], time_low)
  28. binary.BigEndian.PutUint16(uuid[4:], time_mid)
  29. binary.BigEndian.PutUint16(uuid[6:], time_hi)
  30. binary.BigEndian.PutUint16(uuid[8:], clock_seq)
  31. copy(uuid[10:], nodeID)
  32. return uuid
  33. }