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