/
raw.rs
1841 lines (1621 loc) · 57.4 KB
/
raw.rs
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
use std::{
borrow::Cow,
convert::TryInto,
io::{ErrorKind, Read},
sync::Arc,
};
use serde::{
de::{EnumAccess, Error as SerdeError, IntoDeserializer, MapAccess, VariantAccess},
forward_to_deserialize_any,
Deserializer as SerdeDeserializer,
};
use crate::{
oid::ObjectId,
raw::{RawBinaryRef, RAW_ARRAY_NEWTYPE, RAW_BSON_NEWTYPE, RAW_DOCUMENT_NEWTYPE},
spec::{BinarySubtype, ElementType},
uuid::UUID_NEWTYPE_NAME,
Bson,
DateTime,
Decimal128,
DeserializerOptions,
RawDocument,
Timestamp,
};
use super::{
read_bool,
read_f128,
read_f64,
read_i32,
read_i64,
read_string,
read_u8,
DeserializerHint,
Error,
Result,
MAX_BSON_SIZE,
MIN_CODE_WITH_SCOPE_SIZE,
};
use crate::de::serde::MapDeserializer;
/// Deserializer used to parse and deserialize raw BSON bytes.
pub(crate) struct Deserializer<'de> {
bytes: BsonBuf<'de>,
/// The type of the element currently being deserialized.
///
/// When the Deserializer is initialized, this will be `ElementType::EmbeddedDocument`, as the
/// only top level type is a document. The "embedded" portion is incorrect in this context,
/// but given that there's no difference between deserializing an embedded document and a
/// top level one, the distinction isn't necessary.
current_type: ElementType,
}
/// Enum used to determine what the type of document being deserialized is in
/// `Deserializer::deserialize_document`.
enum DocumentType {
Array,
EmbeddedDocument,
}
impl<'de> Deserializer<'de> {
pub(crate) fn new(buf: &'de [u8], utf8_lossy: bool) -> Self {
Self {
bytes: BsonBuf::new(buf, utf8_lossy),
current_type: ElementType::EmbeddedDocument,
}
}
/// Ensure the entire document was visited, returning an error if not.
/// Will read the trailing null byte if necessary (i.e. the visitor stopped after visiting
/// exactly the number of elements in the document).
fn end_document(&mut self, length_remaining: i32) -> Result<()> {
match length_remaining.cmp(&1) {
std::cmp::Ordering::Equal => {
let nullbyte = read_u8(&mut self.bytes)?;
if nullbyte != 0 {
return Err(Error::custom(format!(
"expected null byte at end of document, got {:#x} instead",
nullbyte
)));
}
}
std::cmp::Ordering::Greater => {
return Err(Error::custom(format!(
"document has bytes remaining that were not visited: {}",
length_remaining
)));
}
std::cmp::Ordering::Less => {
if length_remaining < 0 {
return Err(Error::custom("length of document was too short"));
}
}
}
Ok(())
}
/// Read a string from the BSON.
///
/// If utf8_lossy, this will be an owned string if invalid UTF-8 is encountered in the string,
/// otherwise it will be borrowed.
fn deserialize_str(&mut self) -> Result<Cow<'de, str>> {
self.bytes.read_str()
}
/// Read a null-terminated C style string from the underling BSON.
///
/// If utf8_lossy, this will be an owned string if invalid UTF-8 is encountered in the string,
/// otherwise it will be borrowed.
fn deserialize_cstr(&mut self) -> Result<Cow<'de, str>> {
self.bytes.read_cstr()
}
/// Read an ObjectId from the underling BSON.
///
/// If hinted to use raw BSON, the bytes of the ObjectId will be visited.
/// Otherwise, a map in the shape of the extended JSON format of an ObjectId will be.
fn deserialize_objectid<V>(&mut self, visitor: V, hint: DeserializerHint) -> Result<V::Value>
where
V: serde::de::Visitor<'de>,
{
let oid = ObjectId::from_reader(&mut self.bytes)?;
visitor.visit_map(ObjectIdAccess::new(oid, hint))
}
/// Read a document from the underling BSON, whether it's an array or an actual document.
///
/// If hinted to use raw BSON, the bytes themselves will be visited using a special newtype
/// name. Otherwise, the key-value pairs will be accessed in order, either as part of a
/// `MapAccess` for documents or a `SeqAccess` for arrays.
fn deserialize_document<V>(
&mut self,
visitor: V,
hint: DeserializerHint,
document_type: DocumentType,
) -> Result<V::Value>
where
V: serde::de::Visitor<'de>,
{
let is_array = match document_type {
DocumentType::Array => true,
DocumentType::EmbeddedDocument => false,
};
match hint {
DeserializerHint::RawBson => {
let mut len = self.bytes.slice(4)?;
let len = read_i32(&mut len)?;
let doc = RawDocument::from_bytes(self.bytes.read_slice(len as usize)?)
.map_err(Error::custom)?;
let access = if is_array {
RawDocumentAccess::for_array(doc)
} else {
RawDocumentAccess::new(doc)
};
visitor.visit_map(access)
}
_ if is_array => self.access_document(|access| visitor.visit_seq(access)),
_ => self.access_document(|access| visitor.visit_map(access)),
}
}
/// Construct a `DocumentAccess` and pass it into the provided closure, returning the
/// result of the closure if no other errors are encountered.
fn access_document<F, O>(&mut self, f: F) -> Result<O>
where
F: FnOnce(DocumentAccess<'_, 'de>) -> Result<O>,
{
let mut length_remaining = read_i32(&mut self.bytes)?;
if length_remaining < 4 {
return Err(Error::custom("invalid length, less than min document size"));
}
length_remaining -= 4;
let out = f(DocumentAccess {
root_deserializer: self,
length_remaining: &mut length_remaining,
});
if out.is_ok() {
self.end_document(length_remaining)?;
}
out
}
/// Deserialize the next element type and update `current_type` accordingly.
/// Returns `None` if a null byte is read.
fn deserialize_next_type(&mut self) -> Result<Option<ElementType>> {
let tag = read_u8(&mut self.bytes)?;
if tag == 0 {
return Ok(None);
}
let element_type = ElementType::from(tag)
.ok_or_else(|| Error::custom(format!("invalid element type: {}", tag)))?;
self.current_type = element_type;
Ok(Some(element_type))
}
/// Deserialize the next element in the BSON, using the type of the element along with the
/// provided hint to determine how to visit the data.
fn deserialize_next<V>(&mut self, visitor: V, hint: DeserializerHint) -> Result<V::Value>
where
V: serde::de::Visitor<'de>,
{
if let DeserializerHint::BinarySubtype(expected_st) = hint {
if self.current_type != ElementType::Binary {
return Err(Error::custom(format!(
"expected Binary with subtype {:?}, instead got {:?}",
expected_st, self.current_type
)));
}
}
match self.current_type {
ElementType::Int32 => visitor.visit_i32(read_i32(&mut self.bytes)?),
ElementType::Int64 => visitor.visit_i64(read_i64(&mut self.bytes)?),
ElementType::Double => visitor.visit_f64(read_f64(&mut self.bytes)?),
ElementType::String => match self.deserialize_str()? {
Cow::Borrowed(s) => visitor.visit_borrowed_str(s),
Cow::Owned(string) => visitor.visit_string(string),
},
ElementType::Boolean => visitor.visit_bool(read_bool(&mut self.bytes)?),
ElementType::Null => visitor.visit_unit(),
ElementType::ObjectId => self.deserialize_objectid(visitor, hint),
ElementType::EmbeddedDocument => {
self.deserialize_document(visitor, hint, DocumentType::EmbeddedDocument)
}
ElementType::Array => self.deserialize_document(visitor, hint, DocumentType::Array),
ElementType::Binary => {
let len = read_i32(&mut self.bytes)?;
if !(0..=MAX_BSON_SIZE).contains(&len) {
return Err(Error::invalid_length(
len as usize,
&format!("binary length must be between 0 and {}", MAX_BSON_SIZE).as_str(),
));
}
let subtype = BinarySubtype::from(read_u8(&mut self.bytes)?);
if let DeserializerHint::BinarySubtype(expected_subtype) = hint {
if subtype != expected_subtype {
return Err(Error::custom(format!(
"expected binary subtype {:?} instead got {:?}",
expected_subtype, subtype
)));
}
}
match subtype {
BinarySubtype::Generic => {
visitor.visit_borrowed_bytes(self.bytes.read_slice(len as usize)?)
}
_ => {
let binary = RawBinaryRef::from_slice_with_len_and_payload(
self.bytes.read_slice(len as usize)?,
len,
subtype,
)?;
let mut d = BinaryDeserializer::new(binary, hint);
visitor.visit_map(BinaryAccess {
deserializer: &mut d,
})
}
}
}
ElementType::Undefined => {
visitor.visit_map(RawBsonAccess::new("$undefined", BsonContent::Boolean(true)))
}
ElementType::DateTime => {
let dti = read_i64(&mut self.bytes)?;
let dt = DateTime::from_millis(dti);
let mut d = DateTimeDeserializer::new(dt, hint);
visitor.visit_map(DateTimeAccess {
deserializer: &mut d,
})
}
ElementType::RegularExpression => {
let mut de = RegexDeserializer::new(&mut *self);
visitor.visit_map(RegexAccess::new(&mut de))
}
ElementType::DbPointer => {
let mut de = DbPointerDeserializer::new(&mut *self, hint);
visitor.visit_map(DbPointerAccess::new(&mut de))
}
ElementType::JavaScriptCode => {
let utf8_lossy = self.bytes.utf8_lossy;
match hint {
DeserializerHint::RawBson => visitor.visit_map(RawBsonAccess::new(
"$code",
BsonContent::Str(self.bytes.read_borrowed_str()?),
)),
_ => {
let code = read_string(&mut self.bytes, utf8_lossy)?;
let doc = Bson::JavaScriptCode(code).into_extended_document(false);
visitor.visit_map(MapDeserializer::new(
doc,
DeserializerOptions::builder().human_readable(false).build(),
))
}
}
}
ElementType::JavaScriptCodeWithScope => {
let len = read_i32(&mut self.bytes)?;
if len < MIN_CODE_WITH_SCOPE_SIZE {
return Err(SerdeError::invalid_length(
len.try_into().unwrap_or(0),
&format!(
"CodeWithScope to be at least {} bytes",
MIN_CODE_WITH_SCOPE_SIZE
)
.as_str(),
));
} else if (self.bytes.bytes_remaining() as i32) < len - 4 {
return Err(SerdeError::invalid_length(
len.try_into().unwrap_or(0),
&format!(
"CodeWithScope to be at most {} bytes",
self.bytes.bytes_remaining()
)
.as_str(),
));
}
let mut de = CodeWithScopeDeserializer::new(&mut *self, hint, len - 4);
let out = visitor.visit_map(CodeWithScopeAccess::new(&mut de));
if de.length_remaining != 0 {
return Err(SerdeError::invalid_length(
len.try_into().unwrap_or(0),
&format!(
"CodeWithScope length {} bytes greater than actual length",
de.length_remaining
)
.as_str(),
));
}
out
}
ElementType::Symbol => {
let utf8_lossy = self.bytes.utf8_lossy;
match hint {
DeserializerHint::RawBson => visitor.visit_map(RawBsonAccess::new(
"$symbol",
BsonContent::Str(self.bytes.read_borrowed_str()?),
)),
_ => {
let symbol = read_string(&mut self.bytes, utf8_lossy)?;
let doc = Bson::Symbol(symbol).into_extended_document(false);
visitor.visit_map(MapDeserializer::new(
doc,
DeserializerOptions::builder().human_readable(false).build(),
))
}
}
}
ElementType::Timestamp => {
let ts = Timestamp::from_reader(&mut self.bytes)?;
let mut d = TimestampDeserializer::new(ts);
visitor.visit_map(TimestampAccess {
deserializer: &mut d,
})
}
ElementType::Decimal128 => {
let d128 = read_f128(&mut self.bytes)?;
visitor.visit_map(Decimal128Access::new(d128))
}
ElementType::MaxKey => {
visitor.visit_map(RawBsonAccess::new("$maxKey", BsonContent::Int32(1)))
}
ElementType::MinKey => {
visitor.visit_map(RawBsonAccess::new("$minKey", BsonContent::Int32(1)))
}
}
}
}
impl<'de, 'a> serde::de::Deserializer<'de> for &'a mut Deserializer<'de> {
type Error = Error;
#[inline]
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
where
V: serde::de::Visitor<'de>,
{
self.deserialize_next(visitor, DeserializerHint::None)
}
#[inline]
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
where
V: serde::de::Visitor<'de>,
{
match self.current_type {
ElementType::Null => visitor.visit_none(),
_ => visitor.visit_some(self),
}
}
fn deserialize_enum<V>(
self,
_name: &str,
_variants: &'static [&'static str],
visitor: V,
) -> Result<V::Value>
where
V: serde::de::Visitor<'de>,
{
match self.current_type {
ElementType::String => visitor.visit_enum(self.deserialize_str()?.into_deserializer()),
ElementType::EmbeddedDocument => {
self.access_document(|access| visitor.visit_enum(access))
}
t => Err(Error::custom(format!("expected enum, instead got {:?}", t))),
}
}
fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value>
where
V: serde::de::Visitor<'de>,
{
match self.current_type {
ElementType::ObjectId => visitor.visit_borrowed_bytes(self.bytes.read_slice(12)?),
_ => self.deserialize_any(visitor),
}
}
fn deserialize_newtype_struct<V>(self, name: &'static str, visitor: V) -> Result<V::Value>
where
V: serde::de::Visitor<'de>,
{
match name {
UUID_NEWTYPE_NAME => self.deserialize_next(
visitor,
DeserializerHint::BinarySubtype(BinarySubtype::Uuid),
),
RAW_BSON_NEWTYPE => self.deserialize_next(visitor, DeserializerHint::RawBson),
RAW_DOCUMENT_NEWTYPE => {
if self.current_type != ElementType::EmbeddedDocument {
return Err(serde::de::Error::custom(format!(
"expected raw document, instead got {:?}",
self.current_type
)));
}
self.deserialize_next(visitor, DeserializerHint::RawBson)
}
RAW_ARRAY_NEWTYPE => {
if self.current_type != ElementType::Array {
return Err(serde::de::Error::custom(format!(
"expected raw array, instead got {:?}",
self.current_type
)));
}
self.deserialize_next(visitor, DeserializerHint::RawBson)
}
_ => visitor.visit_newtype_struct(self),
}
}
fn is_human_readable(&self) -> bool {
false
}
forward_to_deserialize_any! {
bool char str byte_buf unit unit_struct string
identifier seq tuple tuple_struct struct
map ignored_any i8 i16 i32 i64 u8 u16 u32 u64 f32 f64
}
}
/// Struct for accessing documents for deserialization purposes.
/// This is used to deserialize maps, structs, sequences, and enums.
struct DocumentAccess<'d, 'de> {
root_deserializer: &'d mut Deserializer<'de>,
length_remaining: &'d mut i32,
}
impl<'d, 'de> DocumentAccess<'d, 'de> {
/// Read the next element type and update the root deserializer with it.
///
/// Returns `Ok(None)` if the document has been fully read and has no more elements.
fn read_next_type(&mut self) -> Result<Option<ElementType>> {
let t = self.read(|s| s.root_deserializer.deserialize_next_type())?;
if t.is_none() && *self.length_remaining != 0 {
return Err(Error::custom(format!(
"got null byte but still have length {} remaining",
self.length_remaining
)));
}
Ok(t)
}
/// Executes a closure that reads from the BSON bytes and returns an error if the number of
/// bytes read exceeds length_remaining.
///
/// A mutable reference to this `DocumentAccess` is passed into the closure.
fn read<F, O>(&mut self, f: F) -> Result<O>
where
F: FnOnce(&mut Self) -> Result<O>,
{
let start_bytes = self.root_deserializer.bytes.bytes_read();
let out = f(self);
let bytes_read = self.root_deserializer.bytes.bytes_read() - start_bytes;
*self.length_remaining -= bytes_read as i32;
if *self.length_remaining < 0 {
return Err(Error::custom("length of document too short"));
}
out
}
/// Read the next value from the document.
fn read_next_value<V>(&mut self, seed: V) -> Result<V::Value>
where
V: serde::de::DeserializeSeed<'de>,
{
self.read(|s| seed.deserialize(&mut *s.root_deserializer))
}
}
impl<'d, 'de> serde::de::MapAccess<'de> for DocumentAccess<'d, 'de> {
type Error = crate::de::Error;
fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
where
K: serde::de::DeserializeSeed<'de>,
{
if self.read_next_type()?.is_none() {
return Ok(None);
}
self.read(|s| {
seed.deserialize(DocumentKeyDeserializer {
root_deserializer: &mut *s.root_deserializer,
})
})
.map(Some)
}
fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
where
V: serde::de::DeserializeSeed<'de>,
{
self.read_next_value(seed)
}
}
impl<'d, 'de> serde::de::SeqAccess<'de> for DocumentAccess<'d, 'de> {
type Error = Error;
fn next_element_seed<S>(&mut self, seed: S) -> Result<Option<S::Value>>
where
S: serde::de::DeserializeSeed<'de>,
{
if self.read_next_type()?.is_none() {
return Ok(None);
}
let _index = self.read(|s| s.root_deserializer.deserialize_cstr())?;
self.read_next_value(seed).map(Some)
}
}
impl<'d, 'de> EnumAccess<'de> for DocumentAccess<'d, 'de> {
type Error = Error;
type Variant = Self;
fn variant_seed<V>(mut self, seed: V) -> Result<(V::Value, Self::Variant)>
where
V: serde::de::DeserializeSeed<'de>,
{
if self.read_next_type()?.is_none() {
return Err(Error::EndOfStream);
}
let key = self.read(|s| {
seed.deserialize(DocumentKeyDeserializer {
root_deserializer: &mut *s.root_deserializer,
})
})?;
Ok((key, self))
}
}
impl<'d, 'de> VariantAccess<'de> for DocumentAccess<'d, 'de> {
type Error = Error;
fn unit_variant(self) -> Result<()> {
Err(Error::custom(
"expected a string enum, got a document instead",
))
}
fn newtype_variant_seed<S>(mut self, seed: S) -> Result<S::Value>
where
S: serde::de::DeserializeSeed<'de>,
{
self.read_next_value(seed)
}
fn tuple_variant<V>(mut self, _len: usize, visitor: V) -> Result<V::Value>
where
V: serde::de::Visitor<'de>,
{
self.read(|s| s.root_deserializer.deserialize_seq(visitor))
}
fn struct_variant<V>(mut self, _fields: &'static [&'static str], visitor: V) -> Result<V::Value>
where
V: serde::de::Visitor<'de>,
{
self.read(|s| s.root_deserializer.deserialize_map(visitor))
}
}
/// Deserializer used specifically for deserializing a document's cstring keys.
struct DocumentKeyDeserializer<'d, 'de> {
root_deserializer: &'d mut Deserializer<'de>,
}
impl<'d, 'de> serde::de::Deserializer<'de> for DocumentKeyDeserializer<'d, 'de> {
type Error = Error;
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
where
V: serde::de::Visitor<'de>,
{
let s = self.root_deserializer.deserialize_cstr()?;
match s {
Cow::Borrowed(b) => visitor.visit_borrowed_str(b),
Cow::Owned(string) => visitor.visit_string(string),
}
}
fn deserialize_enum<V>(
self,
_name: &str,
_variants: &'static [&'static str],
visitor: V,
) -> Result<V::Value>
where
V: serde::de::Visitor<'de>,
{
visitor.visit_enum(
self.root_deserializer
.deserialize_cstr()?
.into_deserializer(),
)
}
fn deserialize_newtype_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value>
where
V: serde::de::Visitor<'de>,
{
visitor.visit_newtype_struct(self)
}
fn is_human_readable(&self) -> bool {
false
}
forward_to_deserialize_any! {
bool char str bytes byte_buf option unit unit_struct string
identifier seq tuple tuple_struct struct map
ignored_any i8 i16 i32 i64 u8 u16 u32 u64 f32 f64
}
}
/// Deserializer used to deserialize the given field name without any copies.
struct FieldDeserializer {
field_name: &'static str,
}
impl<'de> serde::de::Deserializer<'de> for FieldDeserializer {
type Error = Error;
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
where
V: serde::de::Visitor<'de>,
{
visitor.visit_borrowed_str(self.field_name)
}
fn deserialize_newtype_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value>
where
V: serde::de::Visitor<'de>,
{
visitor.visit_newtype_struct(self)
}
fn is_human_readable(&self) -> bool {
false
}
serde::forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string seq
bytes byte_buf map struct option unit
ignored_any unit_struct tuple_struct tuple enum identifier
}
}
/// A `MapAccess` used to deserialize entire documents as chunks of bytes without deserializing
/// the individual key/value pairs.
struct RawDocumentAccess<'d> {
deserializer: RawDocumentDeserializer<'d>,
/// Whether the first key has been deserialized yet or not.
deserialized_first: bool,
/// Whether or not this document being deserialized is for an array or not.
array: bool,
}
impl<'de> RawDocumentAccess<'de> {
fn new(doc: &'de RawDocument) -> Self {
Self {
deserializer: RawDocumentDeserializer { raw_doc: doc },
deserialized_first: false,
array: false,
}
}
fn for_array(doc: &'de RawDocument) -> Self {
Self {
deserializer: RawDocumentDeserializer { raw_doc: doc },
deserialized_first: false,
array: true,
}
}
}
impl<'de> serde::de::MapAccess<'de> for RawDocumentAccess<'de> {
type Error = Error;
fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
where
K: serde::de::DeserializeSeed<'de>,
{
if !self.deserialized_first {
self.deserialized_first = true;
// the newtype name will indicate to the `RawBson` enum that the incoming
// bytes are meant to be treated as a document or array instead of a binary value.
seed.deserialize(FieldDeserializer {
field_name: if self.array {
RAW_ARRAY_NEWTYPE
} else {
RAW_DOCUMENT_NEWTYPE
},
})
.map(Some)
} else {
Ok(None)
}
}
fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
where
V: serde::de::DeserializeSeed<'de>,
{
seed.deserialize(self.deserializer)
}
}
#[derive(Clone, Copy)]
struct RawDocumentDeserializer<'a> {
raw_doc: &'a RawDocument,
}
impl<'de> serde::de::Deserializer<'de> for RawDocumentDeserializer<'de> {
type Error = Error;
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
where
V: serde::de::Visitor<'de>,
{
visitor.visit_borrowed_bytes(self.raw_doc.as_bytes())
}
fn is_human_readable(&self) -> bool {
false
}
serde::forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string seq
bytes byte_buf map struct option unit newtype_struct
ignored_any unit_struct tuple_struct tuple enum identifier
}
}
struct ObjectIdAccess {
oid: ObjectId,
visited: bool,
hint: DeserializerHint,
}
impl ObjectIdAccess {
fn new(oid: ObjectId, hint: DeserializerHint) -> Self {
Self {
oid,
visited: false,
hint,
}
}
}
impl<'de> serde::de::MapAccess<'de> for ObjectIdAccess {
type Error = Error;
fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
where
K: serde::de::DeserializeSeed<'de>,
{
if self.visited {
return Ok(None);
}
self.visited = true;
seed.deserialize(FieldDeserializer { field_name: "$oid" })
.map(Some)
}
fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
where
V: serde::de::DeserializeSeed<'de>,
{
seed.deserialize(ObjectIdDeserializer {
oid: self.oid,
hint: self.hint,
})
}
}
struct ObjectIdDeserializer {
oid: ObjectId,
hint: DeserializerHint,
}
impl<'de> serde::de::Deserializer<'de> for ObjectIdDeserializer {
type Error = Error;
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
where
V: serde::de::Visitor<'de>,
{
// save an allocation when deserializing to raw bson
match self.hint {
DeserializerHint::RawBson => visitor.visit_bytes(&self.oid.bytes()),
_ => visitor.visit_string(self.oid.to_hex()),
}
}
fn is_human_readable(&self) -> bool {
false
}
serde::forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string seq
bytes byte_buf map struct option unit newtype_struct
ignored_any unit_struct tuple_struct tuple enum identifier
}
}
pub(crate) struct Decimal128Access {
decimal: Decimal128,
visited: bool,
}
impl Decimal128Access {
pub(crate) fn new(decimal: Decimal128) -> Self {
Self {
decimal,
visited: false,
}
}
}
impl<'de> serde::de::MapAccess<'de> for Decimal128Access {
type Error = Error;
fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
where
K: serde::de::DeserializeSeed<'de>,
{
if self.visited {
return Ok(None);
}
self.visited = true;
seed.deserialize(FieldDeserializer {
field_name: "$numberDecimalBytes",
})
.map(Some)
}
fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
where
V: serde::de::DeserializeSeed<'de>,
{
seed.deserialize(Decimal128Deserializer(self.decimal))
}
}
struct Decimal128Deserializer(Decimal128);
impl<'de> serde::de::Deserializer<'de> for Decimal128Deserializer {
type Error = Error;
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
where
V: serde::de::Visitor<'de>,
{
visitor.visit_bytes(&self.0.bytes)
}
fn is_human_readable(&self) -> bool {
false
}
serde::forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string seq
bytes byte_buf map struct option unit newtype_struct
ignored_any unit_struct tuple_struct tuple enum identifier
}
}
enum TimestampDeserializationStage {
TopLevel,
Time,
Increment,
Done,
}
struct TimestampAccess<'d> {
deserializer: &'d mut TimestampDeserializer,
}
impl<'de, 'd> serde::de::MapAccess<'de> for TimestampAccess<'d> {
type Error = Error;
fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
where
K: serde::de::DeserializeSeed<'de>,
{
match self.deserializer.stage {
TimestampDeserializationStage::TopLevel => seed
.deserialize(FieldDeserializer {
field_name: "$timestamp",
})
.map(Some),
TimestampDeserializationStage::Time => seed
.deserialize(FieldDeserializer { field_name: "t" })
.map(Some),
TimestampDeserializationStage::Increment => seed
.deserialize(FieldDeserializer { field_name: "i" })
.map(Some),
TimestampDeserializationStage::Done => Ok(None),
}
}
fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
where
V: serde::de::DeserializeSeed<'de>,
{
seed.deserialize(&mut *self.deserializer)
}
}
struct TimestampDeserializer {
ts: Timestamp,
stage: TimestampDeserializationStage,
}
impl TimestampDeserializer {
fn new(ts: Timestamp) -> Self {
Self {
ts,
stage: TimestampDeserializationStage::TopLevel,
}
}
}
impl<'de, 'a> serde::de::Deserializer<'de> for &'a mut TimestampDeserializer {
type Error = Error;
fn deserialize_any<V>(mut self, visitor: V) -> Result<V::Value>
where
V: serde::de::Visitor<'de>,
{
match self.stage {