本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

166 lines
4.0KB

  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. "bytes"
  12. "crypto/rand"
  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. // NewObjectID generates a new ObjectID.
  31. func NewObjectID() ObjectID {
  32. return NewObjectIDFromTimestamp(time.Now())
  33. }
  34. // NewObjectIDFromTimestamp generates a new ObjectID based on the given time.
  35. func NewObjectIDFromTimestamp(timestamp time.Time) ObjectID {
  36. var b [12]byte
  37. binary.BigEndian.PutUint32(b[0:4], uint32(timestamp.Unix()))
  38. copy(b[4:9], processUnique[:])
  39. putUint24(b[9:12], atomic.AddUint32(&objectIDCounter, 1))
  40. return b
  41. }
  42. // Timestamp extracts the time part of the ObjectId.
  43. func (id ObjectID) Timestamp() time.Time {
  44. unixSecs := binary.BigEndian.Uint32(id[0:4])
  45. return time.Unix(int64(unixSecs), 0).UTC()
  46. }
  47. // Hex returns the hex encoding of the ObjectID as a string.
  48. func (id ObjectID) Hex() string {
  49. return hex.EncodeToString(id[:])
  50. }
  51. func (id ObjectID) String() string {
  52. return fmt.Sprintf("ObjectID(%q)", id.Hex())
  53. }
  54. // IsZero returns true if id is the empty ObjectID.
  55. func (id ObjectID) IsZero() bool {
  56. return bytes.Equal(id[:], NilObjectID[:])
  57. }
  58. // ObjectIDFromHex creates a new ObjectID from a hex string. It returns an error if the hex string is not a
  59. // valid ObjectID.
  60. func ObjectIDFromHex(s string) (ObjectID, error) {
  61. b, err := hex.DecodeString(s)
  62. if err != nil {
  63. return NilObjectID, err
  64. }
  65. if len(b) != 12 {
  66. return NilObjectID, ErrInvalidHex
  67. }
  68. var oid [12]byte
  69. copy(oid[:], b[:])
  70. return oid, nil
  71. }
  72. // MarshalJSON returns the ObjectID as a string
  73. func (id ObjectID) MarshalJSON() ([]byte, error) {
  74. return json.Marshal(id.Hex())
  75. }
  76. // UnmarshalJSON populates the byte slice with the ObjectID. If the byte slice is 64 bytes long, it
  77. // will be populated with the hex representation of the ObjectID. If the byte slice is twelve bytes
  78. // long, it will be populated with the BSON representation of the ObjectID. Otherwise, it will
  79. // return an error.
  80. func (id *ObjectID) UnmarshalJSON(b []byte) error {
  81. var err error
  82. switch len(b) {
  83. case 12:
  84. copy(id[:], b)
  85. default:
  86. // Extended JSON
  87. var res interface{}
  88. err := json.Unmarshal(b, &res)
  89. if err != nil {
  90. return err
  91. }
  92. str, ok := res.(string)
  93. if !ok {
  94. m, ok := res.(map[string]interface{})
  95. if !ok {
  96. return errors.New("not an extended JSON ObjectID")
  97. }
  98. oid, ok := m["$oid"]
  99. if !ok {
  100. return errors.New("not an extended JSON ObjectID")
  101. }
  102. str, ok = oid.(string)
  103. if !ok {
  104. return errors.New("not an extended JSON ObjectID")
  105. }
  106. }
  107. if len(str) != 24 {
  108. return fmt.Errorf("cannot unmarshal into an ObjectID, the length must be 12 but it is %d", len(str))
  109. }
  110. _, err = hex.Decode(id[:], []byte(str))
  111. if err != nil {
  112. return err
  113. }
  114. }
  115. return err
  116. }
  117. func processUniqueBytes() [5]byte {
  118. var b [5]byte
  119. _, err := io.ReadFull(rand.Reader, b[:])
  120. if err != nil {
  121. panic(fmt.Errorf("cannot initialize objectid package with crypto.rand.Reader: %v", err))
  122. }
  123. return b
  124. }
  125. func readRandomUint32() uint32 {
  126. var b [4]byte
  127. _, err := io.ReadFull(rand.Reader, b[:])
  128. if err != nil {
  129. panic(fmt.Errorf("cannot initialize objectid package with crypto.rand.Reader: %v", err))
  130. }
  131. return (uint32(b[0]) << 0) | (uint32(b[1]) << 8) | (uint32(b[2]) << 16) | (uint32(b[3]) << 24)
  132. }
  133. func putUint24(b []byte, v uint32) {
  134. b[0] = byte(v >> 16)
  135. b[1] = byte(v >> 8)
  136. b[2] = byte(v)
  137. }
上海开阖软件有限公司 沪ICP备12045867号-1