-
Notifications
You must be signed in to change notification settings - Fork 0
/
element.go
351 lines (270 loc) · 7.69 KB
/
element.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package birch
import (
"fmt"
"io"
"strconv"
"github.com/tychoish/birch/bsonerr"
"github.com/tychoish/birch/bsontype"
"github.com/tychoish/birch/elements"
)
// Element represents a BSON element, i.e. key-value pair of a BSON document.
//
// NOTE: Element cannot be the value of a map nor a property of a struct without special handling.
// The default encoders and decoders will not process Element correctly. To do so would require
// information loss since an Element contains a key, but the keys used when encoding a struct are
// the struct field names. Instead of using an Element, use a Value as the property of a struct
// field as that is the correct type in this circumstance.
type Element struct {
value *Value
}
func newElement(start uint32, offset uint32) *Element {
return &Element{value: &Value{start: start, offset: offset}}
}
// Copy creates a new Element which has a copy of the content from
// original value, but is otherwise entirely independent.
func (e *Element) Copy() *Element {
return &Element{value: e.value.Copy()}
}
// Value returns the value associated with the BSON element.
func (e *Element) Value() *Value {
return e.value
}
// Validate validates the element and returns its total size.
func (e *Element) Validate() (uint32, error) {
if e == nil {
return 0, bsonerr.NilElement
}
if e.value == nil {
return 0, bsonerr.UninitializedElement
}
var total uint32 = 1
n, err := e.validateKey()
total += n
if err != nil {
return total, err
}
n, err = e.value.validate(false)
total += n
if err != nil {
return total, err
}
return total, nil
}
func (e *Element) validateKey() (uint32, error) {
if e.value.data == nil {
return 0, bsonerr.UninitializedElement
}
pos := e.value.start + 1
end := e.value.offset
var total uint32
if end > uint32(len(e.value.data)) {
end = uint32(len(e.value.data))
}
for ; pos < end && e.value.data[pos] != '\x00'; pos++ {
total++
}
if pos == end || e.value.data[pos] != '\x00' {
return total, bsonerr.InvalidKey
}
total++
return total, nil
}
// Key returns the key for this element.
// It returns the empty string if the element is not initialized.
func (e *Element) Key() string {
if e == nil || e.value == nil || e.value.offset == 0 || e.value.data == nil {
return ""
}
return string(e.value.data[e.value.start+1 : e.value.offset-1])
}
// WriteTo implements the io.WriterTo interface.
func (e *Element) WriteTo(w io.Writer) (int64, error) {
val, err := e.MarshalBSON()
if err != nil {
return 0, err
}
n, err := w.Write(val)
return int64(n), err
}
func (e *Element) writeElement(key bool, start uint, writer any) (int64, error) {
// TODO(skriptble): Figure out if we want to use uint or uint32 and
// standardize across all packages.
var total int64
size, err := e.Validate()
if err != nil {
return 0, err
}
switch w := writer.(type) {
case []byte:
n, err := e.writeByteSlice(key, start, size, w)
if err != nil {
return 0, errTooSmall
}
total += n
case io.Writer:
return e.WriteTo(w)
default:
return 0, bsonerr.InvalidWriter
}
return total, nil
}
// writeByteSlice handles writing this element to a slice of bytes.
func (e *Element) writeByteSlice(key bool, start uint, size uint32, b []byte) (int64, error) {
var startToWrite uint
needed := start + uint(size)
if key {
startToWrite = uint(e.value.start)
} else {
startToWrite = uint(e.value.offset)
// Fewer bytes are needed if the key isn't being written.
needed -= uint(e.value.offset) - uint(e.value.start) - 1
}
if uint(len(b)) < needed {
return 0, errTooSmall
}
var n int
switch e.Value().Type() {
case bsontype.EmbeddedDocument:
if e.value.d == nil {
n = copy(b[start:], e.value.data[startToWrite:e.value.start+size])
break
}
header := e.value.offset - e.value.start
size -= header
if key {
n += copy(b[start:], e.value.data[startToWrite:e.value.offset])
start += uint(n)
}
nn, err := e.value.d.writeByteSlice(start, size, b)
n += int(nn)
if err != nil {
return int64(n), err
}
case bsontype.Array:
if e.value.d == nil {
n = copy(b[start:], e.value.data[startToWrite:e.value.start+size])
break
}
header := e.value.offset - e.value.start
size -= header
if key {
n += copy(b[start:], e.value.data[startToWrite:e.value.offset])
start += uint(n)
}
arr := &Array{doc: e.value.d}
nn, err := arr.writeByteSlice(start, size, b)
n += int(nn)
if err != nil {
return int64(n), err
}
case bsontype.CodeWithScope:
// Get length of code
codeStart := e.value.offset + 4
codeLength := readi32(e.value.data[codeStart : codeStart+4])
if e.value.d != nil {
lengthWithoutScope := 4 + 4 + codeLength
scopeLength, err := e.value.d.Validate()
if err != nil {
return 0, err
}
codeWithScopeLength := lengthWithoutScope + int32(scopeLength)
if _, err = elements.Int32.Encode(uint(e.value.offset), e.value.data, codeWithScopeLength); err != nil {
return int64(n), err
}
codeEnd := e.value.offset + uint32(lengthWithoutScope)
n += copy(
b[start:],
e.value.data[startToWrite:codeEnd])
start += uint(n)
nn, err := e.value.d.writeByteSlice(start, scopeLength, b)
n += int(nn)
if err != nil {
return int64(n), err
}
break
}
// Get length of scope
scopeStart := codeStart + 4 + uint32(codeLength)
scopeLength := readi32(e.value.data[scopeStart : scopeStart+4])
// Calculate end of entire CodeWithScope value
codeWithScopeEnd := int32(scopeStart) + scopeLength
// Set the length of the value
codeWithScopeLength := codeWithScopeEnd - int32(e.value.offset)
if _, err := elements.Int32.Encode(uint(e.value.offset), e.value.data, codeWithScopeLength); err != nil {
return 0, err
}
fallthrough
default:
n = copy(b[start:], e.value.data[startToWrite:e.value.start+size])
}
return int64(n), nil
}
// MarshalBSON implements the Marshaler interface.
func (e *Element) MarshalBSON() ([]byte, error) {
size, err := e.Validate()
if err != nil {
return nil, err
}
b := make([]byte, size)
if _, err = e.writeByteSlice(true, 0, size, b); err != nil {
return nil, err
}
return b, nil
}
// String implements the fmt.Stringer interface.
func (e *Element) String() string {
val := e.Value().Interface()
if s, ok := val.(string); ok && e.Value().Type() == bsontype.String {
val = strconv.Quote(s)
}
return fmt.Sprintf(`bson.Element{[%s]"%s": %v}`, e.Value().Type(), e.Key(), val)
}
// Equal compares this element to element and returns true if they are equal.
func (e *Element) Equal(e2 *Element) bool {
if e == nil && e2 == nil {
return true
}
if e == nil || e2 == nil {
return false
}
if e.Key() != e2.Key() {
return false
}
return e.value.Equal(e2.value)
}
func elemsFromValues(values []*Value) []*Element {
elems := make([]*Element, len(values))
for i, v := range values {
if v == nil {
elems[i] = nil
} else {
elems[i] = &Element{v}
}
}
return elems
}
func convertValueToElem(key string, v *Value) *Element {
if v == nil || v.offset == 0 || v.data == nil {
return nil
}
keyLen := len(key)
// We add the length of the data so when we compare values
// we don't have extra space at the end of the data property.
d := make([]byte, 2+len(key)+len(v.data[v.offset:]))
d[0] = v.data[v.start]
copy(d[1:keyLen+1], key)
d[keyLen+1] = 0x00
copy(d[keyLen+2:], v.data[v.offset:])
elem := newElement(0, uint32(keyLen+2))
elem.value.data = d
elem.value.d = nil
if v.d != nil {
elem.value.d = v.d.Copy()
}
return elem
}