-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathextjson.go
1722 lines (1536 loc) · 44.2 KB
/
extjson.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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2020 by David A. Golden. All rights reserved.
//
// 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 jibby
import (
"bytes"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"fmt"
"io"
"math"
"regexp"
"sort"
"strconv"
"time"
"github.com/google/uuid"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/bsontype"
"go.mongodb.org/mongo-driver/bson/primitive"
)
// Efficient extended JSON detection:
//
// The longest extended JSON key is $regularExpression at 18 letters
// The shortest extended JSON key is $oid at 3 letters. Any $-prefixed
// key outside those lengths isn't extended JSON. We can switch on
// length to avoid a linear scan against all keys.
//
// $oid
// $code
// $date
// $type -- option for legacy $binary
// $uuid -- treated as $binary with subtype 4
// $scope
// $regex -- legacy regular expression
// $binary
// $maxKey
// $minKey
// $symbol
// $options -- option for legacy regular expression
// $dbPointer
// $numberInt
// $timestamp
// $undefined
// $numberLong
// $numberDouble
// $numberDecimal
// $regularExpression
// handleExtJSON is called from convertObject to potentially replace a JSON
// object with a non-document BSON value instead. If it returns (nil, nil), it
// means that the input is not extended JSON and that no bytes were consumed
// from the input. If it succeeds, then the extended JSON object will have been
// consumed.
//
// If/when a type is definitively determined, the `typeBytePos` of
// `out` will be overwritten the discovered type.
//
// This function generally only validates/dispatches to subroutines. Those
// functions are responsible for consuming the full extended JSON object,
// including the closing terminator.
func (d *Decoder) handleExtJSON(out []byte, typeBytePos int) ([]byte, error) {
// Peek ahead for longest possible extjson key plus surrounding quotes.
buf, err := d.json.Peek(20)
if err != nil {
// May have peeked to end of input, so EOF is OK.
if err != io.EOF {
return nil, err
}
}
// Skip past opening quote (which must have existed to get to handleExtJSON)
buf = buf[1:]
// Common case: If $ doesn't follow opening quote, then not extended JSON.
if len(buf) > 0 && buf[0] != '$' {
return nil, nil
}
// Isolate key
quotePos := bytes.IndexByte(buf, '"')
if quotePos < 0 {
// Key is longer than `$regularExpression"`, so not valid extended JSON.
return nil, nil
}
key := buf[0:quotePos]
// When we find a key, we can write a type byte and discard from the input
// buffer the length of that key plus two for the surrounding quotes. In
// ambiguous cases, we can't assign a type or discard, so we defer that
// to a corresponding subroutine.
switch len(key) {
case 4: // $oid
if bytes.Equal(key, jsonOID) {
overwriteTypeByte(out, typeBytePos, bsonObjectID)
_, _ = d.json.Discard(6)
return d.convertOID(out)
}
return nil, nil
case 5: // $code $date $type $uuid
if bytes.Equal(key, jsonCode) {
// Still don't know if this is code or code w/scope, so can't
// assign type yet, but we can consume the key.
_, _ = d.json.Discard(7)
return d.convertCode(out, typeBytePos)
} else if bytes.Equal(key, jsonDate) {
overwriteTypeByte(out, typeBytePos, bsonDateTime)
_, _ = d.json.Discard(7)
return d.convertDate(out)
} else if bytes.Equal(key, jsonType) {
// Still don't know if this is binary or a $type query operator, so
// can't assign type or discard anything yet.
return d.convertType(out, typeBytePos)
} else if bytes.Equal(key, jsonUUID) {
overwriteTypeByte(out, typeBytePos, bsonBinary)
_, _ = d.json.Discard(7)
return d.convertUUID(out)
}
return nil, nil
case 6: // $scope $regex
if bytes.Equal(key, jsonScope) {
overwriteTypeByte(out, typeBytePos, bsonCodeWithScope)
_, _ = d.json.Discard(8)
return d.convertScope(out)
} else if bytes.Equal(key, jsonRegex) {
// Still don't know if this is legacy $regex or a $regex query
// operator so can't assign type or discard anything yet.
return d.convertRegex(out, typeBytePos)
}
return nil, nil
case 7: // $binary $maxKey $minKey $symbol
if bytes.Equal(key, jsonBinary) {
overwriteTypeByte(out, typeBytePos, bsonBinary)
_, _ = d.json.Discard(9)
return d.convertBinary(out)
} else if bytes.Equal(key, jsonMaxKey) {
overwriteTypeByte(out, typeBytePos, bsonMaxKey)
_, _ = d.json.Discard(9)
return d.convertMinMaxKey(out)
} else if bytes.Equal(key, jsonMinKey) {
overwriteTypeByte(out, typeBytePos, bsonMinKey)
_, _ = d.json.Discard(9)
return d.convertMinMaxKey(out)
} else if bytes.Equal(key, jsonSymbol) {
overwriteTypeByte(out, typeBytePos, bsonSymbol)
_, _ = d.json.Discard(9)
return d.convertSymbol(out)
}
return nil, nil
case 8: // $options
if bytes.Equal(key, jsonOptions) {
// Still don't know if this is legacy $regex or non-extJSON
// so can't assign type or discard anything yet.
return d.convertOptions(out, typeBytePos)
}
return nil, nil
case 10: // $dbPointer $numberInt $timestamp $undefined
if bytes.Equal(key, jsonDbPointer) {
overwriteTypeByte(out, typeBytePos, bsonDBPointer)
_, _ = d.json.Discard(12)
return d.convertDBPointer(out)
}
if bytes.Equal(key, jsonNumberInt) {
overwriteTypeByte(out, typeBytePos, bsonInt32)
_, _ = d.json.Discard(12)
return d.convertNumberInt(out)
}
if bytes.Equal(key, jsonTimestamp) {
overwriteTypeByte(out, typeBytePos, bsonTimestamp)
_, _ = d.json.Discard(12)
return d.convertTimestamp(out)
}
if bytes.Equal(key, jsonUndefined) {
overwriteTypeByte(out, typeBytePos, bsonUndefined)
_, _ = d.json.Discard(12)
return d.convertUndefined(out)
}
return nil, nil
case 11: // $numberLong
if bytes.Equal(key, jsonNumberLong) {
overwriteTypeByte(out, typeBytePos, bsonInt64)
_, _ = d.json.Discard(13)
return d.convertNumberLong(out)
}
return nil, nil
case 13: // $numberDouble
if bytes.Equal(key, jsonNumberDouble) {
overwriteTypeByte(out, typeBytePos, bsonDouble)
_, _ = d.json.Discard(15)
return d.convertNumberDouble(out)
}
return nil, nil
case 14: // $numberDecimal
if bytes.Equal(key, jsonNumberDecimal) {
overwriteTypeByte(out, typeBytePos, bsonDecimal128)
_, _ = d.json.Discard(16)
return d.convertNumberDecimal(out)
}
return nil, nil
case 18: // $regularExpression
if bytes.Equal(key, jsonRegularExpression) {
overwriteTypeByte(out, typeBytePos, bsonRegex)
_, _ = d.json.Discard(20)
return d.convertRegularExpression(out)
}
return nil, nil
default:
// Not an extended JSON key
return nil, nil
}
}
// convertOID starts after the `"$oid"` key.
func (d *Decoder) convertOID(out []byte) ([]byte, error) {
// consume ':'
err := d.readNameSeparator()
if err != nil {
return nil, err
}
// consume opening quote of string
err = d.readQuoteStart()
if err != nil {
return nil, err
}
// peek ahead for 24 bytes and closing quote
buf, err := d.json.Peek(25)
if err != nil {
return nil, newReadError(err)
}
if buf[24] != '"' {
return nil, d.parseError(nil, "ill-formed $oid")
}
// extract hex string and convert/write
var x [12]byte
xs := x[0:12]
_, err = hex.Decode(xs, buf[0:24])
if err != nil {
return nil, d.parseError(nil, fmt.Sprintf("objectID conversion: %v", err))
}
out = append(out, xs...)
_, _ = d.json.Discard(25)
// Must end with document terminator
err = d.readObjectTerminator()
if err != nil {
return nil, err
}
return out, nil
}
// convertCode starts after the `"$code"` key. We need to find out if it's just
// $code or followed by $scope to determine type byte.
//
// The problem with translation is that BSON code is just "string" and BSON code
// w/scope is "int32 string document", so we can't copy the code string to the
// BSON output until after we see if there is a $scope key so we know if we need
// to add the int32 length part.
func (d *Decoder) convertCode(out []byte, typeBytePos int) ([]byte, error) {
// Whether code string or code w/scope, need to reserve at least 4 bytes for
// a length, as both start that way.
lengthPos := len(out)
out = append(out, emptyLength...)
// Consume ':'
err := d.readNameSeparator()
if err != nil {
return nil, err
}
// Consume '"'
err = d.readQuoteStart()
if err != nil {
return nil, err
}
// Make a copy of code cstring to defer writing.
scratchP := d.scratchPool.Get().(*[]byte)
defer func() { d.scratchPool.Put(scratchP) }()
codeCString := (*scratchP)[0:0]
codeCString, err = d.convertCString(codeCString)
// Code string could contain null byte because it's represented as
// length-prefixed BSON string.
if err != nil && err != errNullEscape {
return nil, err
}
// Look for value separator or object terminator.
ch, err := d.readAfterWS()
if err != nil {
return nil, newReadError(err)
}
switch ch {
case '}':
// Just $code
overwriteTypeByte(out, typeBytePos, bsonCode)
out = append(out, codeCString...)
// BSON code length is CString length, not including length bytes
strLength := len(out) - lengthPos - 4
overwriteLength(out, lengthPos, strLength)
case ',':
// Maybe followed by $scope
err = d.readQuoteStart()
if err != nil {
return nil, err
}
err = d.readSpecificKey(jsonScope)
if err != nil {
return nil, err
}
// We know it's code w/ scope: add additional length bytes for the
// Cstring, then convert the scope object.
overwriteTypeByte(out, typeBytePos, bsonCodeWithScope)
strLengthPos := len(out)
out = append(out, emptyLength...)
out = append(out, codeCString...)
strLength := len(out) - strLengthPos - 4
overwriteLength(out, strLengthPos, strLength)
err = d.readCharAfterWS('{')
if err != nil {
return nil, err
}
out, err = d.convertObject(out, topContainer)
if err != nil {
return nil, err
}
// BSON code w/scope length is total length including length bytes
cwsLength := len(out) - lengthPos
overwriteLength(out, lengthPos, cwsLength)
// Must end with document terminator
err = d.readObjectTerminator()
if err != nil {
return nil, err
}
default:
return nil, d.parseError([]byte{ch}, "expected value separator or end of object")
}
return out, nil
}
// convertDate starts after the `"$date"` key. The value might be
// an ISO-8601 string or might be a $numberLong object.
func (d *Decoder) convertDate(out []byte) ([]byte, error) {
// Consume ':'
err := d.readNameSeparator()
if err != nil {
return nil, err
}
ch, err := d.readAfterWS()
if err != nil {
return nil, err
}
switch ch {
case '"':
// Shortest ISO-8601 is `YYYY-MM-DDTHH:MM:SSZ` (20 chars); longest is
// `YYYY-MM-DDTHH:MM:SS.sss+HH:MM` (29 chars). Plus we need the closing
// quote. Peek a little further in case extra precision is given
// (counter to the spec).
buf, err := d.peekBoundedQuote(21, 48, "ISO 8601 datetime")
if err != nil {
return nil, err
}
epochMillis, err := parseISO8601toEpochMillis(buf)
if err != nil {
return nil, d.parseError(nil, err.Error())
}
_, _ = d.json.Discard(len(buf) + 1)
var x [8]byte
xs := x[0:8]
binary.LittleEndian.PutUint64(xs, uint64(epochMillis))
out = append(out, xs...)
case '{':
err = d.readQuoteStart()
if err != nil {
return nil, err
}
err = d.readSpecificKey(jsonNumberLong)
if err != nil {
return nil, err
}
// readSpecificKey eats ':' but convertNumberLong wants it so unread it
_ = d.json.UnreadByte()
out, err = d.convertNumberLong(out)
if err != nil {
return nil, err
}
case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
_ = d.json.UnreadByte()
// Unread and reread as Int64
epochMillis, err := d.readInt64()
if err != nil {
return nil, err
}
var x [8]byte
xs := x[0:8]
binary.LittleEndian.PutUint64(xs, uint64(epochMillis))
out = append(out, xs...)
default:
return nil, d.parseError([]byte{ch}, "invalid value for $date")
}
// Must end with document terminator
err = d.readObjectTerminator()
if err != nil {
return nil, err
}
return out, nil
}
// convertType starts after the opening quote of the `"$type"` key. We need to
// distinguish between Extended JSON $type or something else. We decode to a
// scratch buffer and look for exactly "$type" and "$binary".
func (d *Decoder) convertType(out []byte, typeBytePos int) ([]byte, error) {
// Slow path: look for exactly $type and $binary
var err error
scratchP := d.scratchPool.Get().(*[]byte)
defer func() { d.scratchPool.Put(scratchP) }()
scratch := (*scratchP)[0:0]
scratch, err = d.convertObject(scratch, topContainer)
if err != nil {
return nil, err
}
var sawBinary, sawType, sawOther int
var binaryValue, subTypeValue bson.RawValue
elements, _ := bson.Raw(scratch).Elements()
for _, e := range elements {
switch e.Key() {
case "$binary":
sawBinary++
binaryValue = e.Value()
case "$type":
sawType++
subTypeValue = e.Value()
default:
sawOther++
}
}
// If not exactly the extended JSON document we're looking for, copy scratch
// to output as a BSON document.
if sawBinary != 1 || sawType != 1 || sawOther != 0 ||
binaryValue.Type != bsontype.String || subTypeValue.Type != bsontype.String {
overwriteTypeByte(out, typeBytePos, bsonDocument)
out = append(out, scratch...)
return out, nil
}
// If we reach here, then confirmed this as a binary BSON type
overwriteTypeByte(out, typeBytePos, bsonBinary)
lengthPos := len(out)
out = append(out, emptyLength...)
// Append the subtype byte
subType, err := decodeBinarySubType([]byte(subTypeValue.StringValue()))
if err != nil {
return nil, fmt.Errorf("error decoding binary $type: %s", err)
}
out = append(out, subType)
// Decode the binary payload
enc := base64.StdEncoding.WithPadding('=')
payload, err := enc.DecodeString(binaryValue.StringValue())
if err != nil {
return nil, fmt.Errorf("error parsing base64 data: %s", err)
}
binLength := len(payload)
// For binary subtype 2, the byte payload must have the length repeated,
if subType == 2 {
// Extend out with payload length bytes before writing payload
innerLenPos := len(out)
out = append(out, emptyLength...)
overwriteLength(out, innerLenPos, binLength)
binLength += 4
}
out = append(out, payload...)
overwriteLength(out, lengthPos, binLength)
// We don't check for object terminator here because it was already
// consumed in reading the object into the scratch buffer.
return out, nil
}
// convertBinarySubType starts after the opening quote of the string holding hex
// bytes of the value.
func (d *Decoder) convertBinarySubType(out []byte, subTypeBytePos int) ([]byte, byte, error) {
subTypeBytes, err := d.peekBoundedQuote(2, 3, "binary subtype")
if err != nil {
return nil, 0, err
}
subType, err := decodeBinarySubType(subTypeBytes)
if err != nil {
return nil, 0, d.parseError(nil, err.Error())
}
overwriteTypeByte(out, subTypeBytePos, subType)
_, _ = d.json.Discard(len(subTypeBytes) + 1)
return out, subType, nil
}
// convertScope starts after the `"$scope"` key. Having a leading $scope means
// this is code w/ scope, but we have to buffer the scope document and write it
// to the destination after we convert the $code string that follows.
func (d *Decoder) convertScope(out []byte) ([]byte, error) {
// consume ':'
err := d.readNameSeparator()
if err != nil {
return nil, err
}
// Reserve length bytes for full code w/ scope length
cwsLengthPos := len(out)
out = append(out, emptyLength...)
// Copy $scope into a temporary BSON document
scratchP := d.scratchPool.Get().(*[]byte)
defer func() { d.scratchPool.Put(scratchP) }()
scopeDoc := (*scratchP)[0:0]
err = d.readCharAfterWS('{')
if err != nil {
return nil, err
}
scopeDoc, err = d.convertObject(scopeDoc, topContainer)
if err != nil {
return nil, err
}
// Find and copy $code to the output
err = d.readCharAfterWS(',')
if err != nil {
return nil, err
}
err = d.readQuoteStart()
if err != nil {
return nil, err
}
err = d.readSpecificKey(jsonCode)
if err != nil {
return nil, err
}
err = d.readQuoteStart()
if err != nil {
return nil, err
}
out, err = d.convertString(out)
if err != nil {
return nil, err
}
// Write buffered $scope
out = append(out, scopeDoc...)
// BSON code w/scope length is total length including length bytes
cwsLength := len(out) - cwsLengthPos
overwriteLength(out, cwsLengthPos, cwsLength)
return out, nil
}
var dollarRegexQueryOpRe = regexp.MustCompile(`^"\$regex"\s*:\s*\{`)
// convertRegex starts on the opening quote of `"$regex"`. We need to
// distinguish between Extended JSON $regex or MongoDB $regex query operator.
// If we can peek far enough, we can check with regular expresssions.
//
// Both query and extended JSON allow { "$regex": "...", "$options": "..." } so
// we choose to treat that like extended JSON. If converted to a BSON regular
// expression and sent as a query to a MongoDB and it will work either way.
// However, a Javascript query expression like { "$regex": /abc/ } will turn
// into extended JSON like { "$regex" : { <$regex or $regularExpression object>
// } }, so if we see that "$regex" is followed by an object, we treat that as a
// query.
func (d *Decoder) convertRegex(out []byte, typeBytePos int) ([]byte, error) {
// Fast path: Peek ahead some amount and look for $regex with object, which
// we know isn't extended JSON. 16 bytes is enough even with a little extra
// white space.
buf, err := d.json.Peek(16)
if err != nil {
// EOF is OK if we peeked to the end
if err != io.EOF {
return nil, err
}
}
if dollarRegexQueryOpRe.Match(buf) {
return nil, nil
}
return d.convertRegexOptionsSlowPath(out, typeBytePos)
}
// convertRegexOptionsSlowPath: Convert current object to a scratch BSON buffer.
// If it has exactly two keys, $regex and $options, and if both values are
// strings, then we can copy just those pieces into a BSON regex in the output.
// Otherwise, it's not extended JSON and we can copy the scratch buffer to the
// output as a document
func (d *Decoder) convertRegexOptionsSlowPath(out []byte, typeBytePos int) ([]byte, error) {
var err error
scratchP := d.scratchPool.Get().(*[]byte)
defer func() { d.scratchPool.Put(scratchP) }()
scratch := (*scratchP)[0:0]
scratch, err = d.convertObject(scratch, topContainer)
if err != nil {
return nil, err
}
var sawRegex, sawOptions, sawOther int
var regexValue, optionsValue bson.RawValue
elements, _ := bson.Raw(scratch).Elements()
for _, e := range elements {
switch e.Key() {
case "$regex":
sawRegex++
regexValue = e.Value()
case "$options":
sawOptions++
optionsValue = e.Value()
default:
sawOther++
}
}
// If not exactly an extended JSON document, copy scratch to output as
// a BSON document.
if sawRegex != 1 || sawOptions != 1 || sawOther != 0 ||
regexValue.Type != bsontype.String || optionsValue.Type != bsontype.String {
overwriteTypeByte(out, typeBytePos, bsonDocument)
out = append(out, scratch...)
return out, nil
}
// If we reach here, then confirmed this as a regular expression BSON type.
overwriteTypeByte(out, typeBytePos, bsonRegex)
out = append(out, []byte(regexValue.StringValue())...)
out = append(out, nullByte)
opts := []byte(optionsValue.StringValue())
if len(opts) > 1 {
err = sortOptions(opts)
if err != nil {
return nil, err
}
out = append(out, opts...)
}
out = append(out, nullByte)
// We don't check for object terminator here because it was already
// consumed in reading the object into the scratch buffer.
return out, nil
}
// convertBinary starts after the `"$binary"` key. However, we have to
// determine if it is legacy extended JSON, where $binary holds the data and is
// followed by a $type field, or v2 extended JSON where $binary is followed by
// an object that holds the data and subtype.
func (d *Decoder) convertBinary(out []byte) ([]byte, error) {
// consume ':'
err := d.readNameSeparator()
if err != nil {
return nil, err
}
// Determine if this is v1 or v2 $binary
ch, err := d.readAfterWS()
if err != nil {
return nil, newReadError(err)
}
switch ch {
case '{':
out, err = d.convertV2Binary(out)
if err != nil {
return nil, err
}
case '"':
out, err = d.convertV1Binary(out)
if err != nil {
return nil, err
}
default:
return nil, d.parseError([]byte{ch}, "expected object or string")
}
// Must end with document terminator
err = d.readObjectTerminator()
if err != nil {
return nil, err
}
return out, nil
}
// convertV2Binary is called after the opening brace of the object. V2 $binary
// must be an object with keys "base64" and "subType".
func (d *Decoder) convertV2Binary(out []byte) ([]byte, error) {
// write a length placeholder and a subtype byte placeholder
lengthPos := len(out)
out = append(out, emptyLength...)
subTypeBytePos := len(out)
out = append(out, emptyType)
// Need to see exactly 2 keys, subType and base64, in any order.
var sawBase64 bool
var sawSubType bool
var subType byte
for {
// Read the opening quote of the key and peek the key.
err := d.readQuoteStart()
if err != nil {
return nil, err
}
key, err := d.peekBoundedQuote(7, 8, "valid $binary document keys")
if err != nil {
return nil, err
}
switch {
case bytes.Equal(key, jsonSubType):
if sawSubType {
return nil, d.parseError(nil, "subType repeated")
}
sawSubType = true
_, _ = d.json.Discard(len(key) + 1)
err = d.readNameSeparator()
if err != nil {
return nil, err
}
err = d.readQuoteStart()
if err != nil {
return nil, err
}
out, subType, err = d.convertBinarySubType(out, subTypeBytePos)
if err != nil {
return nil, err
}
// If we haven't seen the other key, we expect to see a separator.
if !sawBase64 {
err = d.readCharAfterWS(',')
if err != nil {
return nil, err
}
}
case bytes.Equal(key, jsonBase64):
if sawBase64 {
return nil, d.parseError(nil, "base64 repeated")
}
sawBase64 = true
_, _ = d.json.Discard(len(key) + 1)
err = d.readNameSeparator()
if err != nil {
return nil, err
}
err = d.readQuoteStart()
if err != nil {
return nil, err
}
out, err = d.convertBase64(out)
if err != nil {
return nil, err
}
// If we haven't seen the other key, we expect to see a separator.
if !sawSubType {
err = d.readCharAfterWS(',')
if err != nil {
return nil, err
}
}
default:
return nil, d.parseError(nil, "invalid key for $binary document")
}
if sawBase64 && sawSubType {
break
}
}
// write length of binary payload (added length of the output minux 5 bytes
// for length+type)
binLength := len(out) - lengthPos - 5
// For binary subtype 2, the byte payload must have the length repeated,
// so we need to rearrange the output data. We don't do this by default
// so that the common case avoids copies.
if subType == 2 {
// Extend out by size of length bytes, then slide data down.
out = append(out, emptyLength...)
payloadPos := lengthPos + 5
for i := len(out) - 5; i >= payloadPos; i-- {
out[i+4] = out[i]
}
// Write length to start of payload and increment outer length
overwriteLength(out, payloadPos, binLength)
binLength += 4
}
overwriteLength(out, lengthPos, binLength)
// Must end with document terminator
err := d.readObjectTerminator()
if err != nil {
return nil, err
}
return out, nil
}
// convertV1Binary is called after the opening quote of the base64 payload. v1
// $binary is a string, followed by "$type" and no other keys.
func (d *Decoder) convertV1Binary(out []byte) ([]byte, error) {
// Write a length placeholder and a subtype byte placeholder
lengthPos := len(out)
out = append(out, emptyLength...)
subTypeBytePos := len(out)
out = append(out, emptyType)
var subType byte
// Read the payload
out, err := d.convertBase64(out)
if err != nil {
return nil, err
}
// $type key must be next
err = d.readCharAfterWS(',')
if err != nil {
return nil, err
}
err = d.readQuoteStart()
if err != nil {
return nil, err
}
key, err := d.peekBoundedQuote(6, 6, "$type")
if err != nil {
return nil, err
}
if !bytes.Equal(key, jsonType) {
return nil, d.parseError(nil, "expected $type")
}
_, _ = d.json.Discard(len(key) + 1)
err = d.readNameSeparator()
if err != nil {
return nil, err
}
err = d.readQuoteStart()
if err != nil {
return nil, err
}
out, subType, err = d.convertBinarySubType(out, subTypeBytePos)
if err != nil {
return nil, err
}
// write length of binary payload (added length of the output minux 5 bytes
// for length+type)
binLength := len(out) - lengthPos - 5
// For binary subtype 2, the byte payload must have the length repeated,
// so we need to rearrange the output data. We don't do this by default
// so that the common case avoids copies.
if subType == 2 {
// Extend out by size of length bytes, then slide data down.
out = append(out, emptyLength...)
payloadPos := lengthPos + 5
for i := len(out) - 5; i >= payloadPos; i-- {
out[i+4] = out[i]
}
// Write length to start of payload and increment outer length
overwriteLength(out, payloadPos, binLength)
binLength += 4
}
overwriteLength(out, lengthPos, binLength)
return out, nil
}
// convertUUID starts after the `"$uuid"` key. The value must be a quoted
// string that is a valid UUID representation.
func (d *Decoder) convertUUID(out []byte) ([]byte, error) {
// consume ':'
err := d.readNameSeparator()
if err != nil {
return nil, err
}
err = d.readQuoteStart()
if err != nil {
return nil, err
}
// Peek ahead 33 to 46 characters for min/max UUID string length plus
// closing quote. UUID without dashes is 32 characters; with dashes it's
// 36; with dashes and "urn:uuid:" prefix, it's 45.
buf, err := d.peekBoundedQuote(33, 46, "UUID")
if err != nil {
return nil, err
}
// Process buf into UUID, allowing any formats the uuid library recognizes.
u, err := uuid.ParseBytes(buf)
if err != nil {
return nil, d.parseError(buf, fmt.Sprintf("uuid conversion: %v", err))
}
xs, _ := u.MarshalBinary()
// Write UUID length, subtype byte 0x04, and UUID bytes
lengthPos := len(out)
out = append(out, emptyLength...)
overwriteLength(out, lengthPos, 16)
out = append(out, 0x04)
out = append(out, xs...)
// Discard buffer and trailing quote
_, _ = d.json.Discard(len(buf) + 1)
// Must end with document terminator.
err = d.readObjectTerminator()
if err != nil {
return nil, err
}
return out, nil
}
// convertMinMaxKey starts after the `"$minKey"` or `"$maxKey"` key. In either
// case the type byte is already set and the only value for the key is `1` and
// no futher data has to be written. This function only validates and consumes
// input.
func (d *Decoder) convertMinMaxKey(out []byte) ([]byte, error) {
// consume ':'
err := d.readNameSeparator()
if err != nil {
return nil, err
}
// Rest must be `1` followed by object terminator
err = d.readCharAfterWS('1')
if err != nil {
return nil, err
}
err = d.readObjectTerminator()
if err != nil {
return nil, err
}
return out, nil
}
// convertSymbol starts after the `"$symbol"` key.
func (d *Decoder) convertSymbol(out []byte) ([]byte, error) {
// consume ':'
err := d.readNameSeparator()
if err != nil {
return nil, err
}
// Must have `"` followed by string followed by object terminator
err = d.readCharAfterWS('"')
if err != nil {
return nil, err
}
out, err = d.convertString(out)
if err != nil {
return nil, err
}
err = d.readObjectTerminator()
if err != nil {
return nil, err
}
return out, nil
}
var dollarOptionsQueryOpRe = regexp.MustCompile(`^"\$options"\s*:\s*"[^"]*"\s*,\s*"\$regex"\s*:\s*\{`)