objectid.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. // Copyright (C) MongoDB, Inc. 2017-present.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License"); you may
  4. // not use this file except in compliance with the License. You may obtain
  5. // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  6. //
  7. // Based on gopkg.in/mgo.v2/bson by Gustavo Niemeyer
  8. // See THIRD-PARTY-NOTICES for original license terms.
  9. package primitive
  10. import (
  11. "crypto/rand"
  12. "encoding"
  13. "encoding/binary"
  14. "encoding/hex"
  15. "encoding/json"
  16. "errors"
  17. "fmt"
  18. "io"
  19. "sync/atomic"
  20. "time"
  21. )
  22. // ErrInvalidHex indicates that a hex string cannot be converted to an ObjectID.
  23. var ErrInvalidHex = errors.New("the provided hex string is not a valid ObjectID")
  24. // ObjectID is the BSON ObjectID type.
  25. type ObjectID [12]byte
  26. // NilObjectID is the zero value for ObjectID.
  27. var NilObjectID ObjectID
  28. var objectIDCounter = readRandomUint32()
  29. var processUnique = processUniqueBytes()
  30. var _ encoding.TextMarshaler = ObjectID{}
  31. var _ encoding.TextUnmarshaler = &ObjectID{}
  32. // NewObjectID generates a new ObjectID.
  33. func NewObjectID() ObjectID {
  34. return NewObjectIDFromTimestamp(time.Now())
  35. }
  36. // NewObjectIDFromTimestamp generates a new ObjectID based on the given time.
  37. func NewObjectIDFromTimestamp(timestamp time.Time) ObjectID {
  38. var b [12]byte
  39. binary.BigEndian.PutUint32(b[0:4], uint32(timestamp.Unix()))
  40. copy(b[4:9], processUnique[:])
  41. putUint24(b[9:12], atomic.AddUint32(&objectIDCounter, 1))
  42. return b
  43. }
  44. // Timestamp extracts the time part of the ObjectId.
  45. func (id ObjectID) Timestamp() time.Time {
  46. unixSecs := binary.BigEndian.Uint32(id[0:4])
  47. return time.Unix(int64(unixSecs), 0).UTC()
  48. }
  49. // Hex returns the hex encoding of the ObjectID as a string.
  50. func (id ObjectID) Hex() string {
  51. var buf [24]byte
  52. hex.Encode(buf[:], id[:])
  53. return string(buf[:])
  54. }
  55. func (id ObjectID) String() string {
  56. return fmt.Sprintf("ObjectID(%q)", id.Hex())
  57. }
  58. // IsZero returns true if id is the empty ObjectID.
  59. func (id ObjectID) IsZero() bool {
  60. return id == NilObjectID
  61. }
  62. // ObjectIDFromHex creates a new ObjectID from a hex string. It returns an error if the hex string is not a
  63. // valid ObjectID.
  64. func ObjectIDFromHex(s string) (ObjectID, error) {
  65. if len(s) != 24 {
  66. return NilObjectID, ErrInvalidHex
  67. }
  68. var oid [12]byte
  69. _, err := hex.Decode(oid[:], []byte(s))
  70. if err != nil {
  71. return NilObjectID, err
  72. }
  73. return oid, nil
  74. }
  75. // IsValidObjectID returns true if the provided hex string represents a valid ObjectID and false if not.
  76. //
  77. // Deprecated: Use ObjectIDFromHex and check the error instead.
  78. func IsValidObjectID(s string) bool {
  79. _, err := ObjectIDFromHex(s)
  80. return err == nil
  81. }
  82. // MarshalText returns the ObjectID as UTF-8-encoded text. Implementing this allows us to use ObjectID
  83. // as a map key when marshalling JSON. See https://pkg.go.dev/encoding#TextMarshaler
  84. func (id ObjectID) MarshalText() ([]byte, error) {
  85. return []byte(id.Hex()), nil
  86. }
  87. // UnmarshalText populates the byte slice with the ObjectID. Implementing this allows us to use ObjectID
  88. // as a map key when unmarshalling JSON. See https://pkg.go.dev/encoding#TextUnmarshaler
  89. func (id *ObjectID) UnmarshalText(b []byte) error {
  90. oid, err := ObjectIDFromHex(string(b))
  91. if err != nil {
  92. return err
  93. }
  94. *id = oid
  95. return nil
  96. }
  97. // MarshalJSON returns the ObjectID as a string
  98. func (id ObjectID) MarshalJSON() ([]byte, error) {
  99. return json.Marshal(id.Hex())
  100. }
  101. // UnmarshalJSON populates the byte slice with the ObjectID. If the byte slice is 24 bytes long, it
  102. // will be populated with the hex representation of the ObjectID. If the byte slice is twelve bytes
  103. // long, it will be populated with the BSON representation of the ObjectID. This method also accepts empty strings and
  104. // decodes them as NilObjectID. For any other inputs, an error will be returned.
  105. func (id *ObjectID) UnmarshalJSON(b []byte) error {
  106. // Ignore "null" to keep parity with the standard library. Decoding a JSON null into a non-pointer ObjectID field
  107. // will leave the field unchanged. For pointer values, encoding/json will set the pointer to nil and will not
  108. // enter the UnmarshalJSON hook.
  109. if string(b) == "null" {
  110. return nil
  111. }
  112. var err error
  113. switch len(b) {
  114. case 12:
  115. copy(id[:], b)
  116. default:
  117. // Extended JSON
  118. var res interface{}
  119. err := json.Unmarshal(b, &res)
  120. if err != nil {
  121. return err
  122. }
  123. str, ok := res.(string)
  124. if !ok {
  125. m, ok := res.(map[string]interface{})
  126. if !ok {
  127. return errors.New("not an extended JSON ObjectID")
  128. }
  129. oid, ok := m["$oid"]
  130. if !ok {
  131. return errors.New("not an extended JSON ObjectID")
  132. }
  133. str, ok = oid.(string)
  134. if !ok {
  135. return errors.New("not an extended JSON ObjectID")
  136. }
  137. }
  138. // An empty string is not a valid ObjectID, but we treat it as a special value that decodes as NilObjectID.
  139. if len(str) == 0 {
  140. copy(id[:], NilObjectID[:])
  141. return nil
  142. }
  143. if len(str) != 24 {
  144. return fmt.Errorf("cannot unmarshal into an ObjectID, the length must be 24 but it is %d", len(str))
  145. }
  146. _, err = hex.Decode(id[:], []byte(str))
  147. if err != nil {
  148. return err
  149. }
  150. }
  151. return err
  152. }
  153. func processUniqueBytes() [5]byte {
  154. var b [5]byte
  155. _, err := io.ReadFull(rand.Reader, b[:])
  156. if err != nil {
  157. panic(fmt.Errorf("cannot initialize objectid package with crypto.rand.Reader: %v", err))
  158. }
  159. return b
  160. }
  161. func readRandomUint32() uint32 {
  162. var b [4]byte
  163. _, err := io.ReadFull(rand.Reader, b[:])
  164. if err != nil {
  165. panic(fmt.Errorf("cannot initialize objectid package with crypto.rand.Reader: %v", err))
  166. }
  167. return (uint32(b[0]) << 0) | (uint32(b[1]) << 8) | (uint32(b[2]) << 16) | (uint32(b[3]) << 24)
  168. }
  169. func putUint24(b []byte, v uint32) {
  170. b[0] = byte(v >> 16)
  171. b[1] = byte(v >> 8)
  172. b[2] = byte(v)
  173. }