blob: e4835562f777090c44fd6c3e8df360b8006b3742 [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
7package bsonx
8
9import (
10 "bytes"
11 "fmt"
12
13 "github.com/mongodb/mongo-go-driver/bson/bsontype"
14 "github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore"
15)
16
17// MDoc is an unordered, type safe, concise BSON document representation. This type should not be
18// used if you require ordering of values or duplicate keys.
19type MDoc map[string]Val
20
21// ReadMDoc will create a Doc using the provided slice of bytes. If the
22// slice of bytes is not a valid BSON document, this method will return an error.
23func ReadMDoc(b []byte) (MDoc, error) {
24 doc := make(MDoc, 0)
25 err := doc.UnmarshalBSON(b)
26 if err != nil {
27 return nil, err
28 }
29 return doc, nil
30}
31
32// Copy makes a shallow copy of this document.
33func (d MDoc) Copy() MDoc {
34 d2 := make(MDoc, len(d))
35 for k, v := range d {
36 d2[k] = v
37 }
38 return d2
39}
40
41// Lookup searches the document and potentially subdocuments or arrays for the
42// provided key. Each key provided to this method represents a layer of depth.
43//
44// This method will return an empty Value if they key does not exist. To know if they key actually
45// exists, use LookupErr.
46func (d MDoc) Lookup(key ...string) Val {
47 val, _ := d.LookupErr(key...)
48 return val
49}
50
51// LookupErr searches the document and potentially subdocuments or arrays for the
52// provided key. Each key provided to this method represents a layer of depth.
53func (d MDoc) LookupErr(key ...string) (Val, error) {
54 elem, err := d.LookupElementErr(key...)
55 return elem.Value, err
56}
57
58// LookupElement searches the document and potentially subdocuments or arrays for the
59// provided key. Each key provided to this method represents a layer of depth.
60//
61// This method will return an empty Element if they key does not exist. To know if they key actually
62// exists, use LookupElementErr.
63func (d MDoc) LookupElement(key ...string) Elem {
64 elem, _ := d.LookupElementErr(key...)
65 return elem
66}
67
68// LookupElementErr searches the document and potentially subdocuments for the
69// provided key. Each key provided to this method represents a layer of depth.
70func (d MDoc) LookupElementErr(key ...string) (Elem, error) {
71 // KeyNotFound operates by being created where the error happens and then the depth is
72 // incremented by 1 as each function unwinds. Whenever this function returns, it also assigns
73 // the Key slice to the key slice it has. This ensures that the proper depth is identified and
74 // the proper keys.
75 if len(key) == 0 {
76 return Elem{}, KeyNotFound{Key: key}
77 }
78
79 var elem Elem
80 var err error
81 val, ok := d[key[0]]
82 if !ok {
83 return Elem{}, KeyNotFound{Key: key}
84 }
85
86 if len(key) == 1 {
87 return Elem{Key: key[0], Value: val}, nil
88 }
89
90 switch val.Type() {
91 case bsontype.EmbeddedDocument:
92 switch tt := val.primitive.(type) {
93 case Doc:
94 elem, err = tt.LookupElementErr(key[1:]...)
95 case MDoc:
96 elem, err = tt.LookupElementErr(key[1:]...)
97 }
98 default:
99 return Elem{}, KeyNotFound{Type: val.Type()}
100 }
101 switch tt := err.(type) {
102 case KeyNotFound:
103 tt.Depth++
104 tt.Key = key
105 return Elem{}, tt
106 case nil:
107 return elem, nil
108 default:
109 return Elem{}, err // We can't actually hit this.
110 }
111}
112
113// MarshalBSONValue implements the bsoncodec.ValueMarshaler interface.
114//
115// This method will never return an error.
116func (d MDoc) MarshalBSONValue() (bsontype.Type, []byte, error) {
117 if d == nil {
118 // TODO: Should we do this?
119 return bsontype.Null, nil, nil
120 }
121 data, _ := d.MarshalBSON()
122 return bsontype.EmbeddedDocument, data, nil
123}
124
125// MarshalBSON implements the Marshaler interface.
126//
127// This method will never return an error.
128func (d MDoc) MarshalBSON() ([]byte, error) { return d.AppendMarshalBSON(nil) }
129
130// AppendMarshalBSON marshals Doc to BSON bytes, appending to dst.
131//
132// This method will never return an error.
133func (d MDoc) AppendMarshalBSON(dst []byte) ([]byte, error) {
134 idx, dst := bsoncore.ReserveLength(dst)
135 for k, v := range d {
136 t, data, _ := v.MarshalBSONValue() // Value.MarshalBSONValue never returns an error.
137 dst = append(dst, byte(t))
138 dst = append(dst, k...)
139 dst = append(dst, 0x00)
140 dst = append(dst, data...)
141 }
142 dst = append(dst, 0x00)
143 dst = bsoncore.UpdateLength(dst, idx, int32(len(dst[idx:])))
144 return dst, nil
145}
146
147// UnmarshalBSON implements the Unmarshaler interface.
148func (d *MDoc) UnmarshalBSON(b []byte) error {
149 if d == nil {
150 return ErrNilDocument
151 }
152
153 if err := bsoncore.Document(b).Validate(); err != nil {
154 return err
155 }
156
157 elems, err := bsoncore.Document(b).Elements()
158 if err != nil {
159 return err
160 }
161 var val Val
162 for _, elem := range elems {
163 rawv := elem.Value()
164 err = val.UnmarshalBSONValue(rawv.Type, rawv.Data)
165 if err != nil {
166 return err
167 }
168 (*d)[elem.Key()] = val
169 }
170 return nil
171}
172
173// Equal compares this document to another, returning true if they are equal.
174func (d MDoc) Equal(id IDoc) bool {
175 switch tt := id.(type) {
176 case MDoc:
177 d2 := tt
178 if len(d) != len(d2) {
179 return false
180 }
181 for key, value := range d {
182 value2, ok := d2[key]
183 if !ok {
184 return false
185 }
186 if !value.Equal(value2) {
187 return false
188 }
189 }
190 case Doc:
191 unique := make(map[string]struct{}, 0)
192 for _, elem := range tt {
193 unique[elem.Key] = struct{}{}
194 val, ok := d[elem.Key]
195 if !ok {
196 return false
197 }
198 if !val.Equal(elem.Value) {
199 return false
200 }
201 }
202 if len(unique) != len(d) {
203 return false
204 }
205 case nil:
206 return d == nil
207 default:
208 return false
209 }
210
211 return true
212}
213
214// String implements the fmt.Stringer interface.
215func (d MDoc) String() string {
216 var buf bytes.Buffer
217 buf.Write([]byte("bson.Document{"))
218 first := true
219 for key, value := range d {
220 if !first {
221 buf.Write([]byte(", "))
222 }
223 fmt.Fprintf(&buf, "%v", Elem{Key: key, Value: value})
224 first = false
225 }
226 buf.WriteByte('}')
227
228 return buf.String()
229}
230
231func (MDoc) idoc() {}