time.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright 2014 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. guuid "github.com/google/uuid"
  8. )
  9. // A Time represents a time as the number of 100's of nanoseconds since 15 Oct
  10. // 1582.
  11. type Time = guuid.Time
  12. // GetTime returns the current Time (100s of nanoseconds since 15 Oct 1582) and
  13. // clock sequence as well as adjusting the clock sequence as needed. An error
  14. // is returned if the current time cannot be determined.
  15. func GetTime() (Time, uint16, error) { return guuid.GetTime() }
  16. // ClockSequence returns the current clock sequence, generating one if not
  17. // already set. The clock sequence is only used for Version 1 UUIDs.
  18. //
  19. // The uuid package does not use global static storage for the clock sequence or
  20. // the last time a UUID was generated. Unless SetClockSequence a new random
  21. // clock sequence is generated the first time a clock sequence is requested by
  22. // ClockSequence, GetTime, or NewUUID. (section 4.2.1.1) sequence is generated
  23. // for
  24. func ClockSequence() int { return guuid.ClockSequence() }
  25. // SetClockSeq sets the clock sequence to the lower 14 bits of seq. Setting to
  26. // -1 causes a new sequence to be generated.
  27. func SetClockSequence(seq int) { guuid.SetClockSequence(seq) }
  28. // Time returns the time in 100s of nanoseconds since 15 Oct 1582 encoded in
  29. // uuid. It returns false if uuid is not valid. The time is only well defined
  30. // for version 1 and 2 UUIDs.
  31. func (uuid UUID) Time() (Time, bool) {
  32. if len(uuid) != 16 {
  33. return 0, false
  34. }
  35. time := int64(binary.BigEndian.Uint32(uuid[0:4]))
  36. time |= int64(binary.BigEndian.Uint16(uuid[4:6])) << 32
  37. time |= int64(binary.BigEndian.Uint16(uuid[6:8])&0xfff) << 48
  38. return Time(time), true
  39. }
  40. // ClockSequence returns the clock sequence encoded in uuid. It returns false
  41. // if uuid is not valid. The clock sequence is only well defined for version 1
  42. // and 2 UUIDs.
  43. func (uuid UUID) ClockSequence() (int, bool) {
  44. if len(uuid) != 16 {
  45. return 0, false
  46. }
  47. return int(binary.BigEndian.Uint16(uuid[8:10])) & 0x3fff, true
  48. }