Debian Codegraph @

src/de/serde.rs

raw
1 use std::{
2 borrow::Cow,
3 convert::{TryFrom, TryInto},
4 fmt,
5 vec,
6 };
7
8 use serde::de::{
9 self,
10 Deserialize,
11 DeserializeSeed,
12 Deserializer as _,
13 EnumAccess,
14 Error,
15 MapAccess,
16 SeqAccess,
17 Unexpected,
18 VariantAccess,
19 Visitor,
20 };
21 use serde_bytes::ByteBuf;
22
23 use crate::{
24 bson::{Bson, DbPointer, JavaScriptCodeWithScope, Regex, Timestamp},
25 datetime::DateTime,
26 document::{Document, IntoIter},
27 oid::ObjectId,
28 raw::{RawBsonRef, RAW_ARRAY_NEWTYPE, RAW_BSON_NEWTYPE, RAW_DOCUMENT_NEWTYPE},
29 spec::BinarySubtype,
30 uuid::UUID_NEWTYPE_NAME,
31 Binary,
32 Decimal128,
33 };
34
35 use super::{raw::Decimal128Access, DeserializerHint};
36
37 pub(crate) struct BsonVisitor;
38
39 struct ObjectIdVisitor;
40
41 impl<'de> Visitor<'de> for ObjectIdVisitor {
42 type Value = ObjectId;
43
44 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
45 formatter.write_str("expecting an ObjectId")
46 }
47
48 #[inline]
49 fn visit_str<E>(self, value: &str) -> std::result::Result<Self::Value, E>
50 where
51 E: serde::de::Error,
52 {
53 ObjectId::parse_str(value).map_err(|_| {
54 E::invalid_value(
55 Unexpected::Str(value),
56 &"24-character, big-endian hex string",
57 )
58 })
59 }
60
61 #[inline]
62 fn visit_bytes<E>(self, v: &[u8]) -> std::result::Result<Self::Value, E>
63 where
64 E: serde::de::Error,
65 {
66 let bytes: [u8; 12] = v
67 .try_into()
68 .map_err(|_| E::invalid_length(v.len(), &"12 bytes"))?;
69 Ok(ObjectId::from_bytes(bytes))
70 }
71
72 #[inline]
73 fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
74 where
75 V: MapAccess<'de>,
76 {
77 match BsonVisitor.visit_map(&mut visitor)? {
78 Bson::ObjectId(oid) => Ok(oid),
79 bson => {
80 let err = format!(
81 "expected map containing extended-JSON formatted ObjectId, instead found {}",
82 bson
83 );
84 Err(de::Error::custom(err))
85 }
86 }
87 }
88 }
89
90 impl<'de> Deserialize<'de> for ObjectId {
91 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
92 where
93 D: serde::Deserializer<'de>,
94 {
95 if !deserializer.is_human_readable() {
96 deserializer.deserialize_bytes(ObjectIdVisitor)
97 } else {
98 deserializer.deserialize_any(ObjectIdVisitor)
99 }
100 }
101 }
102
103 impl<'de> Deserialize<'de> for Document {
104 /// Deserialize this value given this [`Deserializer`].
105 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
106 where
107 D: de::Deserializer<'de>,
108 {
109 deserializer.deserialize_map(BsonVisitor).and_then(|bson| {
110 if let Bson::Document(doc) = bson {
111 Ok(doc)
112 } else {
113 let err = format!("expected document, found extended JSON data type: {}", bson);
114 Err(de::Error::invalid_type(Unexpected::Map, &&err[..]))
115 }
116 })
117 }
118 }
119
120 impl<'de> Deserialize<'de> for Bson {
121 #[inline]
122 fn deserialize<D>(deserializer: D) -> Result<Bson, D::Error>
123 where
124 D: de::Deserializer<'de>,
125 {
126 deserializer.deserialize_any(BsonVisitor)
127 }
128 }
129
130 impl<'de> Visitor<'de> for BsonVisitor {
131 type Value = Bson;
132
133 fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
134 f.write_str("a Bson")
135 }
136
137 #[inline]
138 fn visit_bool<E>(self, value: bool) -> Result<Bson, E>
139 where
140 E: Error,
141 {
142 Ok(Bson::Boolean(value))
143 }
144
145 #[inline]
146 fn visit_i8<E>(self, value: i8) -> Result<Bson, E>
147 where
148 E: Error,
149 {
150 Ok(Bson::Int32(value as i32))
151 }
152
153 #[inline]
154 fn visit_u8<E>(self, value: u8) -> Result<Bson, E>
155 where
156 E: Error,
157 {
158 convert_unsigned_to_signed(value as u64)
159 }
160
161 #[inline]
162 fn visit_i16<E>(self, value: i16) -> Result<Bson, E>
163 where
164 E: Error,
165 {
166 Ok(Bson::Int32(value as i32))
167 }
168
169 #[inline]
170 fn visit_u16<E>(self, value: u16) -> Result<Bson, E>
171 where
172 E: Error,
173 {
174 convert_unsigned_to_signed(value as u64)
175 }
176
177 #[inline]
178 fn visit_i32<E>(self, value: i32) -> Result<Bson, E>
179 where
180 E: Error,
181 {
182 Ok(Bson::Int32(value))
183 }
184
185 #[inline]
186 fn visit_u32<E>(self, value: u32) -> Result<Bson, E>
187 where
188 E: Error,
189 {
190 convert_unsigned_to_signed(value as u64)
191 }
192
193 #[inline]
194 fn visit_i64<E>(self, value: i64) -> Result<Bson, E>
195 where
196 E: Error,
197 {
198 Ok(Bson::Int64(value))
199 }
200
201 #[inline]
202 fn visit_u64<E>(self, value: u64) -> Result<Bson, E>
203 where
204 E: Error,
205 {
206 convert_unsigned_to_signed(value)
207 }
208
209 #[inline]
210 fn visit_f64<E>(self, value: f64) -> Result<Bson, E> {
211 Ok(Bson::Double(value))
212 }
213
214 #[inline]
215 fn visit_str<E>(self, value: &str) -> Result<Bson, E>
216 where
217 E: de::Error,
218 {
219 self.visit_string(String::from(value))
220 }
221
222 #[inline]
223 fn visit_string<E>(self, value: String) -> Result<Bson, E> {
224 Ok(Bson::String(value))
225 }
226
227 #[inline]
228 fn visit_none<E>(self) -> Result<Bson, E> {
229 Ok(Bson::Null)
230 }
231
232 #[inline]
233 fn visit_some<D>(self, deserializer: D) -> Result<Bson, D::Error>
234 where
235 D: de::Deserializer<'de>,
236 {
237 deserializer.deserialize_any(self)
238 }
239
240 #[inline]
241 fn visit_unit<E>(self) -> Result<Bson, E> {
242 Ok(Bson::Null)
243 }
244
245 #[inline]
246 fn visit_seq<V>(self, mut visitor: V) -> Result<Bson, V::Error>
247 where
248 V: SeqAccess<'de>,
249 {
250 let mut values = Vec::new();
251
252 while let Some(elem) = visitor.next_element()? {
253 values.push(elem);
254 }
255
256 Ok(Bson::Array(values))
257 }
258
259 fn visit_map<V>(self, mut visitor: V) -> Result<Bson, V::Error>
260 where
261 V: MapAccess<'de>,
262 {
263 use crate::extjson;
264
265 let mut doc = Document::new();
266
267 while let Some(k) = visitor.next_key::<String>()? {
268 match k.as_str() {
269 "$oid" => {
270 enum BytesOrHex<'a> {
271 Bytes([u8; 12]),
272 Hex(Cow<'a, str>),
273 }
274
275 impl<'a, 'de: 'a> Deserialize<'de> for BytesOrHex<'a> {
276 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
277 where
278 D: serde::Deserializer<'de>,
279 {
280 struct BytesOrHexVisitor;
281
282 impl<'de> Visitor<'de> for BytesOrHexVisitor {
283 type Value = BytesOrHex<'de>;
284
285 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
286 write!(formatter, "hexstring or byte array")
287 }
288
289 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
290 where
291 E: Error,
292 {
293 Ok(BytesOrHex::Hex(Cow::Owned(v.to_string())))
294 }
295
296 fn visit_borrowed_str<E>(
297 self,
298 v: &'de str,
299 ) -> Result<Self::Value, E>
300 where
301 E: Error,
302 {
303 Ok(BytesOrHex::Hex(Cow::Borrowed(v)))
304 }
305
306 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
307 where
308 E: Error,
309 {
310 Ok(BytesOrHex::Bytes(v.try_into().map_err(Error::custom)?))
311 }
312 }
313
314 deserializer.deserialize_any(BytesOrHexVisitor)
315 }
316 }
317
318 let bytes_or_hex: BytesOrHex = visitor.next_value()?;
319 match bytes_or_hex {
320 BytesOrHex::Bytes(b) => return Ok(Bson::ObjectId(ObjectId::from_bytes(b))),
321 BytesOrHex::Hex(hex) => {
322 return Ok(Bson::ObjectId(ObjectId::parse_str(&hex).map_err(
323 |_| {
324 V::Error::invalid_value(
325 Unexpected::Str(&hex),
326 &"24-character, big-endian hex string",
327 )
328 },
329 )?));
330 }
331 }
332 }
333 "$symbol" => {
334 let string: String = visitor.next_value()?;
335 return Ok(Bson::Symbol(string));
336 }
337
338 "$numberInt" => {
339 let string: String = visitor.next_value()?;
340 return Ok(Bson::Int32(string.parse().map_err(|_| {
341 V::Error::invalid_value(
342 Unexpected::Str(&string),
343 &"32-bit signed integer as a string",
344 )
345 })?));
346 }
347
348 "$numberLong" => {
349 let string: String = visitor.next_value()?;
350 return Ok(Bson::Int64(string.parse().map_err(|_| {
351 V::Error::invalid_value(
352 Unexpected::Str(&string),
353 &"64-bit signed integer as a string",
354 )
355 })?));
356 }
357
358 "$numberDouble" => {
359 let string: String = visitor.next_value()?;
360 let val = match string.as_str() {
361 "Infinity" => Bson::Double(std::f64::INFINITY),
362 "-Infinity" => Bson::Double(std::f64::NEG_INFINITY),
363 "NaN" => Bson::Double(std::f64::NAN),
364 _ => Bson::Double(string.parse().map_err(|_| {
365 V::Error::invalid_value(
366 Unexpected::Str(&string),
367 &"64-bit signed integer as a string",
368 )
369 })?),
370 };
371 return Ok(val);
372 }
373
374 "$binary" => {
375 let v = visitor.next_value::<extjson::models::BinaryBody>()?;
376 return Ok(Bson::Binary(
377 extjson::models::Binary { body: v }
378 .parse()
379 .map_err(Error::custom)?,
380 ));
381 }
382
383 "$code" => {
384 let code = visitor.next_value::<String>()?;
385 if let Some(key) = visitor.next_key::<String>()? {
386 if key.as_str() == "$scope" {
387 let scope = visitor.next_value::<Document>()?;
388 return Ok(Bson::JavaScriptCodeWithScope(JavaScriptCodeWithScope {
389 code,
390 scope,
391 }));
392 } else {
393 return Err(Error::unknown_field(key.as_str(), &["$scope"]));
394 }
395 } else {
396 return Ok(Bson::JavaScriptCode(code));
397 }
398 }
399
400 "$scope" => {
401 let scope = visitor.next_value::<Document>()?;
402 if let Some(key) = visitor.next_key::<String>()? {
403 if key.as_str() == "$code" {
404 let code = visitor.next_value::<String>()?;
405 return Ok(Bson::JavaScriptCodeWithScope(JavaScriptCodeWithScope {
406 code,
407 scope,
408 }));
409 } else {
410 return Err(Error::unknown_field(key.as_str(), &["$code"]));
411 }
412 } else {
413 return Err(Error::missing_field("$code"));
414 }
415 }
416
417 "$timestamp" => {
418 let ts = visitor.next_value::<extjson::models::TimestampBody>()?;
419 return Ok(Bson::Timestamp(Timestamp {
420 time: ts.t,
421 increment: ts.i,
422 }));
423 }
424
425 "$regularExpression" => {
426 let re = visitor.next_value::<extjson::models::RegexBody>()?;
427 return Ok(Bson::RegularExpression(Regex::new(re.pattern, re.options)));
428 }
429
430 "$dbPointer" => {
431 let dbp = visitor.next_value::<extjson::models::DbPointerBody>()?;
432 return Ok(Bson::DbPointer(DbPointer {
433 id: dbp.id.parse().map_err(Error::custom)?,
434 namespace: dbp.ref_ns,
435 }));
436 }
437
438 "$date" => {
439 let dt = visitor.next_value::<extjson::models::DateTimeBody>()?;
440 return Ok(Bson::DateTime(
441 extjson::models::DateTime { body: dt }
442 .parse()
443 .map_err(Error::custom)?,
444 ));
445 }
446
447 "$maxKey" => {
448 let i = visitor.next_value::<u8>()?;
449 return extjson::models::MaxKey { value: i }
450 .parse()
451 .map_err(Error::custom);
452 }
453
454 "$minKey" => {
455 let i = visitor.next_value::<u8>()?;
456 return extjson::models::MinKey { value: i }
457 .parse()
458 .map_err(Error::custom);
459 }
460
461 "$undefined" => {
462 let b = visitor.next_value::<bool>()?;
463 return extjson::models::Undefined { value: b }
464 .parse()
465 .map_err(Error::custom);
466 }
467
468 "$numberDecimal" => {
469 let string: String = visitor.next_value()?;
470 return Ok(Bson::Decimal128(string.parse::<Decimal128>().map_err(
471 |_| {
472 V::Error::invalid_value(
473 Unexpected::Str(&string),
474 &"decimal128 as a string",
475 )
476 },
477 )?));
478 }
479
480 "$numberDecimalBytes" => {
481 let bytes = visitor.next_value::<ByteBuf>()?;
482 return Ok(Bson::Decimal128(Decimal128::deserialize_from_slice(
483 &bytes,
484 )?));
485 }
486
487 k => {
488 let v = visitor.next_value::<Bson>()?;
489 doc.insert(k, v);
490 }
491 }
492 }
493
494 Ok(Bson::Document(doc))
495 }
496
497 #[inline]
498 fn visit_bytes<E>(self, v: &[u8]) -> Result<Bson, E>
499 where
500 E: Error,
501 {
502 Ok(Bson::Binary(Binary {
503 subtype: BinarySubtype::Generic,
504 bytes: v.to_vec(),
505 }))
506 }
507
508 #[inline]
509 fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Bson, E>
510 where
511 E: Error,
512 {
513 Ok(Bson::Binary(Binary {
514 subtype: BinarySubtype::Generic,
515 bytes: v,
516 }))
517 }
518
519 #[inline]
520 fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
521 where
522 D: serde::Deserializer<'de>,
523 {
524 deserializer.deserialize_any(self)
525 }
526 }
527
528 enum BsonInteger {
529 Int32(i32),
530 Int64(i64),
531 }
532
533 fn _convert_unsigned<E: Error>(value: u64) -> Result<BsonInteger, E> {
534 if let Ok(int32) = i32::try_from(value) {
535 Ok(BsonInteger::Int32(int32))
536 } else if let Ok(int64) = i64::try_from(value) {
537 Ok(BsonInteger::Int64(int64))
538 } else {
539 Err(Error::custom(format!(
540 "cannot represent {} as a signed number",
541 value
542 )))
543 }
544 }
545
546 fn convert_unsigned_to_signed<E>(value: u64) -> Result<Bson, E>
547 where
548 E: Error,
549 {
550 let bi = _convert_unsigned(value)?;
551 match bi {
552 BsonInteger::Int32(i) => Ok(Bson::Int32(i)),
553 BsonInteger::Int64(i) => Ok(Bson::Int64(i)),
554 }
555 }
556
557 pub(crate) fn convert_unsigned_to_signed_raw<'a, E>(value: u64) -> Result<RawBsonRef<'a>, E>
558 where
559 E: Error,
560 {
561 let bi = _convert_unsigned(value)?;
562 match bi {
563 BsonInteger::Int32(i) => Ok(RawBsonRef::Int32(i)),
564 BsonInteger::Int64(i) => Ok(RawBsonRef::Int64(i)),
565 }
566 }
567
568 /// Serde Deserializer
569 pub struct Deserializer {
570 value: Option<Bson>,
571 options: DeserializerOptions,
572 }
573
574 /// Options used to configure a [`Deserializer`]. These can also be passed into
575 /// [`crate::from_bson_with_options`] and [`crate::from_document_with_options`].
576 #[derive(Debug, Clone, Default)]
577 #[non_exhaustive]
578 pub struct DeserializerOptions {
579 /// Whether the [`Deserializer`] should present itself as human readable or not.
580 /// The default is true.
581 pub human_readable: Option<bool>,
582 }
583
584 impl DeserializerOptions {
585 /// Create a builder struct used to construct a [`DeserializerOptions`].
586 pub fn builder() -> DeserializerOptionsBuilder {
587 DeserializerOptionsBuilder {
588 options: Default::default(),
589 }
590 }
591 }
592
593 /// Builder used to construct a [`DeserializerOptions`].
594 pub struct DeserializerOptionsBuilder {
595 options: DeserializerOptions,
596 }
597
598 impl DeserializerOptionsBuilder {
599 /// Set the value for [`DeserializerOptions::human_readable`].
600 pub fn human_readable(mut self, val: impl Into<Option<bool>>) -> Self {
601 self.options.human_readable = val.into();
602 self
603 }
604
605 /// Consume this builder and produce a [`DeserializerOptions`].
606 pub fn build(self) -> DeserializerOptions {
607 self.options
608 }
609 }
610
611 impl Deserializer {
612 /// Construct a new [`Deserializer`] using the default options.
613 pub fn new(value: Bson) -> Deserializer {
614 Deserializer::new_with_options(value, Default::default())
615 }
616
617 /// Create a new [`Deserializer`] using the provided options.
618 pub fn new_with_options(value: Bson, options: DeserializerOptions) -> Self {
619 Deserializer {
620 value: Some(value),
621 options,
622 }
623 }
624
625 fn deserialize_next<'de, V>(
626 mut self,
627 visitor: V,
628 hint: DeserializerHint,
629 ) -> Result<V::Value, crate::de::Error>
630 where
631 V: serde::de::Visitor<'de>,
632 {
633 let value = match self.value.take() {
634 Some(value) => value,
635 None => return Err(crate::de::Error::EndOfStream),
636 };
637
638 let is_rawbson = matches!(hint, DeserializerHint::RawBson);
639
640 if let DeserializerHint::BinarySubtype(expected_subtype) = hint {
641 if let Bson::Binary(ref binary) = value {
642 if binary.subtype != expected_subtype {
643 return Err(Error::custom(format!(
644 "expected Binary with subtype {:?}, instead got subtype {:?}",
645 expected_subtype, binary.subtype
646 )));
647 }
648 }
649 };
650
651 match value {
652 Bson::Double(v) => visitor.visit_f64(v),
653 Bson::String(v) => visitor.visit_string(v),
654 Bson::Array(v) => {
655 let len = v.len();
656 visitor.visit_seq(SeqDeserializer {
657 iter: v.into_iter(),
658 options: self.options,
659 len,
660 })
661 }
662 Bson::Document(v) => visitor.visit_map(MapDeserializer::new(v, self.options)),
663 Bson::Boolean(v) => visitor.visit_bool(v),
664 Bson::Null => visitor.visit_unit(),
665 Bson::Int32(v) => visitor.visit_i32(v),
666 Bson::Int64(v) => visitor.visit_i64(v),
667 Bson::Binary(b) if b.subtype == BinarySubtype::Generic => {
668 visitor.visit_byte_buf(b.bytes)
669 }
670 Bson::Decimal128(d) => visitor.visit_map(Decimal128Access::new(d)),
671 _ => {
672 let doc = value.into_extended_document(is_rawbson);
673 visitor.visit_map(MapDeserializer::new(doc, self.options))
674 }
675 }
676 }
677 }
678
679 macro_rules! forward_to_deserialize {
680 ($(
681 $name:ident ( $( $arg:ident : $ty:ty ),* );
682 )*) => {
683 $(
684 forward_to_deserialize!{
685 func: $name ( $( $arg: $ty ),* );
686 }
687 )*
688 };
689
690 (func: deserialize_enum ( $( $arg:ident : $ty:ty ),* );) => {
691 fn deserialize_enum<V>(
692 self,
693 $(_: $ty,)*
694 _visitor: V,
695 ) -> ::std::result::Result<V::Value, Self::Error>
696 where V: ::serde::de::Visitor<'de>
697 {
698 Err(::serde::de::Error::custom("unexpected Enum"))
699 }
700 };
701
702 (func: $name:ident ( $( $arg:ident : $ty:ty ),* );) => {
703 #[inline]
704 fn $name<V>(
705 self,
706 $(_: $ty,)*
707 visitor: V,
708 ) -> ::std::result::Result<V::Value, Self::Error>
709 where V: ::serde::de::Visitor<'de>
710 {
711 self.deserialize_any(visitor)
712 }
713 };
714 }
715
716 impl<'de> de::Deserializer<'de> for Deserializer {
717 type Error = crate::de::Error;
718
719 fn is_human_readable(&self) -> bool {
720 self.options.human_readable.unwrap_or(true)
721 }
722
723 #[inline]
724 fn deserialize_any<V>(self, visitor: V) -> crate::de::Result<V::Value>
725 where
726 V: Visitor<'de>,
727 {
728 self.deserialize_next(visitor, DeserializerHint::None)
729 }
730
731 #[inline]
732 fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
733 where
734 V: Visitor<'de>,
735 {
736 match self.value {
737 Some(Bson::ObjectId(oid)) if !self.is_human_readable() => {
738 visitor.visit_bytes(&oid.bytes())
739 }
740 _ => self.deserialize_any(visitor),
741 }
742 }
743
744 #[inline]
745 fn deserialize_option<V>(self, visitor: V) -> crate::de::Result<V::Value>
746 where
747 V: Visitor<'de>,
748 {
749 match self.value {
750 Some(Bson::Null) => visitor.visit_none(),
751 Some(_) => visitor.visit_some(self),
752 None => Err(crate::de::Error::EndOfStream),
753 }
754 }
755
756 #[inline]
757 fn deserialize_enum<V>(
758 mut self,
759 _name: &str,
760 _variants: &'static [&'static str],
761 visitor: V,
762 ) -> crate::de::Result<V::Value>
763 where
764 V: Visitor<'de>,
765 {
766 let value = match self.value.take() {
767 Some(Bson::Document(value)) => value,
768 Some(Bson::String(variant)) => {
769 return visitor.visit_enum(EnumDeserializer {
770 val: Bson::String(variant),
771 deserializer: VariantDeserializer {
772 val: None,
773 options: self.options,
774 },
775 });
776 }
777 Some(v) => {
778 return Err(crate::de::Error::invalid_type(
779 v.as_unexpected(),
780 &"expected an enum",
781 ));
782 }
783 None => {
784 return Err(crate::de::Error::EndOfStream);
785 }
786 };
787
788 let mut iter = value.into_iter();
789
790 let (variant, value) = match iter.next() {
791 Some(v) => v,
792 None => {
793 return Err(crate::de::Error::invalid_value(
794 Unexpected::Other("empty document"),
795 &"variant name",
796 ))
797 }
798 };
799
800 // enums are encoded in json as maps with a single key:value pair
801 match iter.next() {
802 Some((k, _)) => Err(crate::de::Error::invalid_value(
803 Unexpected::Map,
804 &format!("expected map with a single key, got extra key \"{}\"", k).as_str(),
805 )),
806 None => visitor.visit_enum(EnumDeserializer {
807 val: Bson::String(variant),
808 deserializer: VariantDeserializer {
809 val: Some(value),
810 options: self.options,
811 },
812 }),
813 }
814 }
815
816 #[inline]
817 fn deserialize_newtype_struct<V>(
818 self,
819 name: &'static str,
820 visitor: V,
821 ) -> crate::de::Result<V::Value>
822 where
823 V: Visitor<'de>,
824 {
825 match name {
826 UUID_NEWTYPE_NAME => self.deserialize_next(
827 visitor,
828 DeserializerHint::BinarySubtype(BinarySubtype::Uuid),
829 ),
830 RAW_BSON_NEWTYPE => self.deserialize_next(visitor, DeserializerHint::RawBson),
831 RAW_DOCUMENT_NEWTYPE => {
832 if !matches!(self.value, Some(Bson::Document(_))) {
833 return Err(serde::de::Error::custom(format!(
834 "expected raw document, instead got {:?}",
835 self.value
836 )));
837 }
838
839 self.deserialize_next(visitor, DeserializerHint::RawBson)
840 }
841 RAW_ARRAY_NEWTYPE => {
842 if !matches!(self.value, Some(Bson::Array(_))) {
843 return Err(serde::de::Error::custom(format!(
844 "expected raw array, instead got {:?}",
845 self.value
846 )));
847 }
848
849 self.deserialize_next(visitor, DeserializerHint::RawBson)
850 }
851 _ => visitor.visit_newtype_struct(self),
852 }
853 }
854
855 forward_to_deserialize! {
856 deserialize_bool();
857 deserialize_u8();
858 deserialize_u16();
859 deserialize_u32();
860 deserialize_u64();
861 deserialize_i8();
862 deserialize_i16();
863 deserialize_i32();
864 deserialize_i64();
865 deserialize_f32();
866 deserialize_f64();
867 deserialize_char();
868 deserialize_str();
869 deserialize_string();
870 deserialize_unit();
871 deserialize_seq();
872 deserialize_map();
873 deserialize_unit_struct(name: &'static str);
874 deserialize_tuple_struct(name: &'static str, len: usize);
875 deserialize_struct(name: &'static str, fields: &'static [&'static str]);
876 deserialize_tuple(len: usize);
877 deserialize_identifier();
878 deserialize_ignored_any();
879 deserialize_byte_buf();
880 }
881 }
882
883 struct EnumDeserializer {
884 val: Bson,
885 deserializer: VariantDeserializer,
886 }
887
888 impl<'de> EnumAccess<'de> for EnumDeserializer {
889 type Error = crate::de::Error;
890 type Variant = VariantDeserializer;
891 fn variant_seed<V>(self, seed: V) -> crate::de::Result<(V::Value, Self::Variant)>
892 where
893 V: DeserializeSeed<'de>,
894 {
895 let dec = Deserializer::new_with_options(self.val, self.deserializer.options.clone());
896 let value = seed.deserialize(dec)?;
897 Ok((value, self.deserializer))
898 }
899 }
900
901 struct VariantDeserializer {
902 val: Option<Bson>,
903 options: DeserializerOptions,
904 }
905
906 impl<'de> VariantAccess<'de> for VariantDeserializer {
907 type Error = crate::de::Error;
908
909 fn unit_variant(mut self) -> crate::de::Result<()> {
910 match self.val.take() {
911 None => Ok(()),
912 Some(val) => {
913 Bson::deserialize(Deserializer::new_with_options(val, self.options)).map(|_| ())
914 }
915 }
916 }
917
918 fn newtype_variant_seed<T>(mut self, seed: T) -> crate::de::Result<T::Value>
919 where
920 T: DeserializeSeed<'de>,
921 {
922 let dec = Deserializer::new_with_options(
923 self.val.take().ok_or(crate::de::Error::EndOfStream)?,
924 self.options,
925 );
926 seed.deserialize(dec)
927 }
928
929 fn tuple_variant<V>(mut self, _len: usize, visitor: V) -> crate::de::Result<V::Value>
930 where
931 V: Visitor<'de>,
932 {
933 match self.val.take().ok_or(crate::de::Error::EndOfStream)? {
934 Bson::Array(fields) => {
935 let de = SeqDeserializer {
936 len: fields.len(),
937 iter: fields.into_iter(),
938 options: self.options,
939 };
940 de.deserialize_any(visitor)
941 }
942 other => Err(crate::de::Error::invalid_type(
943 other.as_unexpected(),
944 &"expected a tuple",
945 )),
946 }
947 }
948
949 fn struct_variant<V>(
950 mut self,
951 _fields: &'static [&'static str],
952 visitor: V,
953 ) -> crate::de::Result<V::Value>
954 where
955 V: Visitor<'de>,
956 {
957 match self.val.take().ok_or(crate::de::Error::EndOfStream)? {
958 Bson::Document(fields) => {
959 let de = MapDeserializer {
960 len: fields.len(),
961 iter: fields.into_iter(),
962 value: None,
963 options: self.options,
964 };
965 de.deserialize_any(visitor)
966 }
967 ref other => Err(crate::de::Error::invalid_type(
968 other.as_unexpected(),
969 &"expected a struct",
970 )),
971 }
972 }
973 }
974
975 struct SeqDeserializer {
976 iter: vec::IntoIter<Bson>,
977 len: usize,
978 options: DeserializerOptions,
979 }
980
981 impl<'de> de::Deserializer<'de> for SeqDeserializer {
982 type Error = crate::de::Error;
983
984 #[inline]
985 fn deserialize_any<V>(self, visitor: V) -> crate::de::Result<V::Value>
986 where
987 V: Visitor<'de>,
988 {
989 if self.len == 0 {
990 visitor.visit_unit()
991 } else {
992 visitor.visit_seq(self)
993 }
994 }
995
996 forward_to_deserialize! {
997 deserialize_bool();
998 deserialize_u8();
999 deserialize_u16();
1000 deserialize_u32();
1001 deserialize_u64();
1002 deserialize_i8();
1003 deserialize_i16();
1004 deserialize_i32();
1005 deserialize_i64();
1006 deserialize_f32();
1007 deserialize_f64();
1008 deserialize_char();
1009 deserialize_str();
1010 deserialize_string();
1011 deserialize_unit();
1012 deserialize_option();
1013 deserialize_seq();
1014 deserialize_bytes();
1015 deserialize_map();
1016 deserialize_unit_struct(name: &'static str);
1017 deserialize_newtype_struct(name: &'static str);
1018 deserialize_tuple_struct(name: &'static str, len: usize);
1019 deserialize_struct(name: &'static str, fields: &'static [&'static str]);
1020 deserialize_tuple(len: usize);
1021 deserialize_enum(name: &'static str, variants: &'static [&'static str]);
1022 deserialize_identifier();
1023 deserialize_ignored_any();
1024 deserialize_byte_buf();
1025 }
1026 }
1027
1028 impl<'de> SeqAccess<'de> for SeqDeserializer {
1029 type Error = crate::de::Error;
1030
1031 fn next_element_seed<T>(&mut self, seed: T) -> crate::de::Result<Option<T::Value>>
1032 where
1033 T: DeserializeSeed<'de>,
1034 {
1035 match self.iter.next() {
1036 None => Ok(None),
1037 Some(value) => {
1038 self.len -= 1;
1039 let de = Deserializer::new_with_options(value, self.options.clone());
1040 match seed.deserialize(de) {
1041 Ok(value) => Ok(Some(value)),
1042 Err(err) => Err(err),
1043 }
1044 }
1045 }
1046 }
1047
1048 fn size_hint(&self) -> Option<usize> {
1049 Some(self.len)
1050 }
1051 }
1052
1053 pub(crate) struct MapDeserializer {
1054 pub(crate) iter: IntoIter,
1055 pub(crate) value: Option<Bson>,
1056 pub(crate) len: usize,
1057 pub(crate) options: DeserializerOptions,
1058 }
1059
1060 impl MapDeserializer {
1061 pub(crate) fn new(doc: Document, options: impl Into<Option<DeserializerOptions>>) -> Self {
1062 let len = doc.len();
1063 MapDeserializer {
1064 iter: doc.into_iter(),
1065 len,
1066 value: None,
1067 options: options.into().unwrap_or_default(),
1068 }
1069 }
1070 }
1071
1072 impl<'de> MapAccess<'de> for MapDeserializer {
1073 type Error = crate::de::Error;
1074
1075 fn next_key_seed<K>(&mut self, seed: K) -> crate::de::Result<Option<K::Value>>
1076 where
1077 K: DeserializeSeed<'de>,
1078 {
1079 match self.iter.next() {
1080 Some((key, value)) => {
1081 self.len -= 1;
1082 self.value = Some(value);
1083
1084 let de = Deserializer::new_with_options(Bson::String(key), self.options.clone());
1085 match seed.deserialize(de) {
1086 Ok(val) => Ok(Some(val)),
1087 Err(e) => Err(e),
1088 }
1089 }
1090 None => Ok(None),
1091 }
1092 }
1093
1094 fn next_value_seed<V>(&mut self, seed: V) -> crate::de::Result<V::Value>
1095 where
1096 V: DeserializeSeed<'de>,
1097 {
1098 let value = self.value.take().ok_or(crate::de::Error::EndOfStream)?;
1099 let de = Deserializer::new_with_options(value, self.options.clone());
1100 seed.deserialize(de)
1101 }
1102
1103 fn size_hint(&self) -> Option<usize> {
1104 Some(self.len)
1105 }
1106 }
1107
1108 impl<'de> de::Deserializer<'de> for MapDeserializer {
1109 type Error = crate::de::Error;
1110
1111 #[inline]
1112 fn deserialize_any<V>(self, visitor: V) -> crate::de::Result<V::Value>
1113 where
1114 V: Visitor<'de>,
1115 {
1116 visitor.visit_map(self)
1117 }
1118
1119 forward_to_deserialize! {
1120 deserialize_bool();
1121 deserialize_u8();
1122 deserialize_u16();
1123 deserialize_u32();
1124 deserialize_u64();
1125 deserialize_i8();
1126 deserialize_i16();
1127 deserialize_i32();
1128 deserialize_i64();
1129 deserialize_f32();
1130 deserialize_f64();
1131 deserialize_char();
1132 deserialize_str();
1133 deserialize_string();
1134 deserialize_unit();
1135 deserialize_option();
1136 deserialize_seq();
1137 deserialize_bytes();
1138 deserialize_map();
1139 deserialize_unit_struct(name: &'static str);
1140 deserialize_newtype_struct(name: &'static str);
1141 deserialize_tuple_struct(name: &'static str, len: usize);
1142 deserialize_struct(name: &'static str, fields: &'static [&'static str]);
1143 deserialize_tuple(len: usize);
1144 deserialize_enum(name: &'static str, variants: &'static [&'static str]);
1145 deserialize_identifier();
1146 deserialize_ignored_any();
1147 deserialize_byte_buf();
1148 }
1149 }
1150
1151 impl<'de> Deserialize<'de> for Timestamp {
1152 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1153 where
1154 D: de::Deserializer<'de>,
1155 {
1156 match Bson::deserialize(deserializer)? {
1157 Bson::Timestamp(timestamp) => Ok(timestamp),
1158 _ => Err(D::Error::custom("expecting Timestamp")),
1159 }
1160 }
1161 }
1162
1163 impl<'de> Deserialize<'de> for Regex {
1164 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1165 where
1166 D: de::Deserializer<'de>,
1167 {
1168 match Bson::deserialize(deserializer)? {
1169 Bson::RegularExpression(regex) => Ok(regex),
1170 _ => Err(D::Error::custom("expecting Regex")),
1171 }
1172 }
1173 }
1174
1175 impl<'de> Deserialize<'de> for JavaScriptCodeWithScope {
1176 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1177 where
1178 D: de::Deserializer<'de>,
1179 {
1180 match Bson::deserialize(deserializer)? {
1181 Bson::JavaScriptCodeWithScope(code_with_scope) => Ok(code_with_scope),
1182 _ => Err(D::Error::custom("expecting JavaScriptCodeWithScope")),
1183 }
1184 }
1185 }
1186
1187 impl<'de> Deserialize<'de> for Binary {
1188 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1189 where
1190 D: de::Deserializer<'de>,
1191 {
1192 match Bson::deserialize(deserializer)? {
1193 Bson::Binary(binary) => Ok(binary),
1194 d => Err(D::Error::custom(format!(
1195 "expecting Binary but got {:?} instead",
1196 d
1197 ))),
1198 }
1199 }
1200 }
1201
1202 impl<'de> Deserialize<'de> for Decimal128 {
1203 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1204 where
1205 D: de::Deserializer<'de>,
1206 {
1207 match Bson::deserialize(deserializer)? {
1208 Bson::Decimal128(d128) => Ok(d128),
1209 o => Err(D::Error::custom(format!(
1210 "expecting Decimal128, got {:?}",
1211 o
1212 ))),
1213 }
1214 }
1215 }
1216
1217 impl<'de> Deserialize<'de> for DateTime {
1218 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1219 where
1220 D: de::Deserializer<'de>,
1221 {
1222 match Bson::deserialize(deserializer)? {
1223 Bson::DateTime(dt) => Ok(dt),
1224 _ => Err(D::Error::custom("expecting DateTime")),
1225 }
1226 }
1227 }
1228
1229 impl<'de> Deserialize<'de> for DbPointer {
1230 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1231 where
1232 D: de::Deserializer<'de>,
1233 {
1234 match Bson::deserialize(deserializer)? {
1235 Bson::DbPointer(db_pointer) => Ok(db_pointer),
1236 _ => Err(D::Error::custom("expecting DbPointer")),
1237 }
1238 }
1239 }