blob: 9eaaa0610690fa2046cd188d23979ea984f5bca7 [file] [log] [blame]
Don Newton379ae252019-04-01 12:17:06 -04001// 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
10package primitive
11
12import (
13 "bytes"
14 "crypto/rand"
15 "encoding/binary"
16 "encoding/hex"
17 "encoding/json"
18 "errors"
19 "fmt"
20 "io"
21 "sync/atomic"
22 "time"
23)
24
25// ErrInvalidHex indicates that a hex string cannot be converted to an ObjectID.
26var ErrInvalidHex = errors.New("the provided hex string is not a valid ObjectID")
27
28// ObjectID is the BSON ObjectID type.
29type ObjectID [12]byte
30
31// NilObjectID is the zero value for ObjectID.
32var NilObjectID ObjectID
33
34var objectIDCounter = readRandomUint32()
35var processUnique = processUniqueBytes()
36
37// NewObjectID generates a new ObjectID.
38func NewObjectID() ObjectID {
39 var b [12]byte
40
41 binary.BigEndian.PutUint32(b[0:4], uint32(time.Now().Unix()))
42 copy(b[4:9], processUnique[:])
43 putUint24(b[9:12], atomic.AddUint32(&objectIDCounter, 1))
44
45 return b
46}
47
48// Hex returns the hex encoding of the ObjectID as a string.
49func (id ObjectID) Hex() string {
50 return hex.EncodeToString(id[:])
51}
52
53func (id ObjectID) String() string {
54 return fmt.Sprintf("ObjectID(%q)", id.Hex())
55}
56
57// IsZero returns true if id is the empty ObjectID.
58func (id ObjectID) IsZero() bool {
59 return bytes.Equal(id[:], NilObjectID[:])
60}
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.
64func ObjectIDFromHex(s string) (ObjectID, error) {
65 b, err := hex.DecodeString(s)
66 if err != nil {
67 return NilObjectID, err
68 }
69
70 if len(b) != 12 {
71 return NilObjectID, ErrInvalidHex
72 }
73
74 var oid [12]byte
75 copy(oid[:], b[:])
76
77 return oid, nil
78}
79
80// MarshalJSON returns the ObjectID as a string
81func (id ObjectID) MarshalJSON() ([]byte, error) {
82 return json.Marshal(id.Hex())
83}
84
85// UnmarshalJSON populates the byte slice with the ObjectID. If the byte slice is 64 bytes long, it
86// will be populated with the hex representation of the ObjectID. If the byte slice is twelve bytes
87// long, it will be populated with the BSON representation of the ObjectID. Otherwise, it will
88// return an error.
89func (id *ObjectID) UnmarshalJSON(b []byte) error {
90 var err error
91 switch len(b) {
92 case 12:
93 copy(id[:], b)
94 default:
95 // Extended JSON
96 var res interface{}
97 err := json.Unmarshal(b, &res)
98 if err != nil {
99 return err
100 }
101 str, ok := res.(string)
102 if !ok {
103 m, ok := res.(map[string]interface{})
104 if !ok {
105 return errors.New("not an extended JSON ObjectID")
106 }
107 oid, ok := m["$oid"]
108 if !ok {
109 return errors.New("not an extended JSON ObjectID")
110 }
111 str, ok = oid.(string)
112 if !ok {
113 return errors.New("not an extended JSON ObjectID")
114 }
115 }
116
117 if len(str) != 24 {
118 return fmt.Errorf("cannot unmarshal into an ObjectID, the length must be 12 but it is %d", len(str))
119 }
120
121 _, err = hex.Decode(id[:], []byte(str))
122 if err != nil {
123 return err
124 }
125 }
126
127 return err
128}
129
130func processUniqueBytes() [5]byte {
131 var b [5]byte
132 _, err := io.ReadFull(rand.Reader, b[:])
133 if err != nil {
134 panic(fmt.Errorf("cannot initialize objectid package with crypto.rand.Reader: %v", err))
135 }
136
137 return b
138}
139
140func readRandomUint32() uint32 {
141 var b [4]byte
142 _, err := io.ReadFull(rand.Reader, b[:])
143 if err != nil {
144 panic(fmt.Errorf("cannot initialize objectid package with crypto.rand.Reader: %v", err))
145 }
146
147 return (uint32(b[0]) << 0) | (uint32(b[1]) << 8) | (uint32(b[2]) << 16) | (uint32(b[3]) << 24)
148}
149
150func putUint24(b []byte, v uint32) {
151 b[0] = byte(v >> 16)
152 b[1] = byte(v >> 8)
153 b[2] = byte(v)
154}