PageRenderTime 170ms CodeModel.GetById 6ms RepoModel.GetById 1ms app.codeStats 0ms

/uuid.go

https://bitbucket.org/agallego/uuid
Go | 77 lines | 32 code | 14 blank | 31 comment | 4 complexity | 06646ec5e4196c40deebafd43ae1aa93 MD5 | raw file
  1. //This pkg implements uuid v4 only.
  2. package uuid
  3. import (
  4. "crypto/rand"
  5. "log"
  6. "fmt"
  7. "bytes"
  8. "regexp"
  9. )
  10. // octet == index: octets inclusive on both ends.
  11. // |octect 0 - 3 | - time_low: The low fields of the timestamp.
  12. //
  13. // |octect 4 - 5 | - time_mid: The mid fields of the timestamp.
  14. //
  15. // |octect 6 - 7 | - time_hi_and_version: The high field of the timestamp multiplexed with the version number.
  16. //
  17. // |octect 8 | - clock_seq_hi_and_reserved: The high fields of the clock sequence multiplexed with the variant.
  18. //
  19. // |octect 9 | - clock_seq_low: The low field of the clock sequence.
  20. //
  21. // |octets 10 - 15| - node: The spatially unique node identifier.
  22. //
  23. type UUID [16]byte
  24. // e.g.:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6
  25. //
  26. // V4 UUID is of the form: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
  27. //
  28. // where x is any hexadecimal digit and y is one of 8, 9, A, or B.
  29. func (id *UUID) String() string {
  30. return fmt.Sprintf("%x-%x-%x-%x-%x", id[:4], id[4:6], id[6:8], id[8:10], id[10:])
  31. }
  32. func (id *UUID) Bytes() []byte {
  33. return id[:]
  34. }
  35. func Equal(lhs *UUID, rhs *UUID) bool {
  36. return bytes.Equal(lhs[:], rhs[:])
  37. }
  38. //The algorithm is as follows:
  39. //1. Set the two most significant bits (bits 6 and 7) of the
  40. // clock_seq_hi_and_reserved to zero and one, respectively.
  41. //2. Set the four most significant bits (bits 12 through 15) of the
  42. // time_hi_and_version field to the 4-bit version number from rfc4122, section 4.1.3
  43. //3. set all other values to randomly (or pseudo-randomly) chosen values.
  44. //Future improvements: use 2 64 bit values from the rand library.
  45. func V4() *UUID {
  46. var retval UUID
  47. n, err := rand.Read(retval[:])
  48. if n != 16 || err != nil {
  49. log.Fatalf("Random bytes read:%d, details:", n, err.Error())
  50. }
  51. // Set the four most significant bits (bits 12 through 15) of the
  52. // time_hi_and_version field to the 4-bit version number from
  53. // Section 4.1.3.
  54. retval[6] = (retval[6] & 0xf) | 0x40
  55. // Set the two most significant bits (bits 6 and 7) of the
  56. // clock_seq_hi_and_reserved to zero and one, respectively.
  57. retval[8] = (retval[8] & 0x3f) | 0x80
  58. return &retval
  59. }
  60. func ValidString(s string) bool{
  61. regex := regexp.MustCompile(`^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$`)
  62. return regex.MatchString(s)
  63. }