Debian Codegraph @

src/ser/serde.rs

raw
1 use serde::ser::{
2 self,
3 Error as SerdeError,
4 Serialize,
5 SerializeMap,
6 SerializeSeq,
7 SerializeStruct,
8 SerializeStructVariant,
9 SerializeTuple,
10 SerializeTupleStruct,
11 SerializeTupleVariant,
12 };
13 use serde_bytes::Bytes;
14
15 use crate::{
16 bson::{Array, Bson, DbPointer, Document, JavaScriptCodeWithScope, Regex, Timestamp},
17 datetime::DateTime,
18 extjson,
19 oid::ObjectId,
20 raw::{RawDbPointerRef, RawRegexRef, RAW_ARRAY_NEWTYPE, RAW_DOCUMENT_NEWTYPE},
21 spec::BinarySubtype,
22 uuid::UUID_NEWTYPE_NAME,
23 Binary,
24 Decimal128,
25 };
26
27 use super::{to_bson_with_options, Error};
28
29 impl Serialize for ObjectId {
30 #[inline]
31 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
32 where
33 S: serde::ser::Serializer,
34 {
35 let mut ser = serializer.serialize_struct("$oid", 1)?;
36 ser.serialize_field("$oid", &self.to_string())?;
37 ser.end()
38 }
39 }
40
41 impl Serialize for Document {
42 #[inline]
43 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
44 where
45 S: ser::Serializer,
46 {
47 let mut state = serializer.serialize_map(Some(self.len()))?;
48 for (k, v) in self {
49 state.serialize_entry(k, v)?;
50 }
51 state.end()
52 }
53 }
54
55 impl Serialize for Bson {
56 #[inline]
57 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
58 where
59 S: ser::Serializer,
60 {
61 match self {
62 Bson::Double(v) => serializer.serialize_f64(*v),
63 Bson::String(v) => serializer.serialize_str(v),
64 Bson::Array(v) => v.serialize(serializer),
65 Bson::Document(v) => v.serialize(serializer),
66 Bson::Boolean(v) => serializer.serialize_bool(*v),
67 Bson::Null => serializer.serialize_unit(),
68 Bson::Int32(v) => serializer.serialize_i32(*v),
69 Bson::Int64(v) => serializer.serialize_i64(*v),
70 Bson::ObjectId(oid) => oid.serialize(serializer),
71 Bson::DateTime(dt) => dt.serialize(serializer),
72 Bson::Binary(b) => b.serialize(serializer),
73 Bson::JavaScriptCode(c) => {
74 let mut state = serializer.serialize_struct("$code", 1)?;
75 state.serialize_field("$code", c)?;
76 state.end()
77 }
78 Bson::JavaScriptCodeWithScope(code_w_scope) => code_w_scope.serialize(serializer),
79 Bson::DbPointer(dbp) => dbp.serialize(serializer),
80 Bson::Symbol(s) => {
81 let mut state = serializer.serialize_struct("$symbol", 1)?;
82 state.serialize_field("$symbol", s)?;
83 state.end()
84 }
85 Bson::RegularExpression(re) => re.serialize(serializer),
86 Bson::Timestamp(t) => t.serialize(serializer),
87 Bson::Decimal128(d) => {
88 let mut state = serializer.serialize_struct("$numberDecimal", 1)?;
89 state.serialize_field("$numberDecimalBytes", Bytes::new(&d.bytes))?;
90 state.end()
91 }
92 Bson::Undefined => {
93 let mut state = serializer.serialize_struct("$undefined", 1)?;
94 state.serialize_field("$undefined", &true)?;
95 state.end()
96 }
97 Bson::MaxKey => {
98 let mut state = serializer.serialize_struct("$maxKey", 1)?;
99 state.serialize_field("$maxKey", &1)?;
100 state.end()
101 }
102 Bson::MinKey => {
103 let mut state = serializer.serialize_struct("$minKey", 1)?;
104 state.serialize_field("$minKey", &1)?;
105 state.end()
106 }
107 }
108 }
109 }
110
111 /// Serde Serializer
112 #[non_exhaustive]
113 pub struct Serializer {
114 options: SerializerOptions,
115 }
116
117 /// Options used to configure a [`Serializer`].
118 #[derive(Debug, Clone, Default)]
119 #[non_exhaustive]
120 pub struct SerializerOptions {
121 /// Whether the [`Serializer`] should present itself as human readable or not.
122 /// The default value is true.
123 pub human_readable: Option<bool>,
124 }
125
126 impl SerializerOptions {
127 /// Create a builder used to construct a new [`SerializerOptions`].
128 pub fn builder() -> SerializerOptionsBuilder {
129 SerializerOptionsBuilder {
130 options: Default::default(),
131 }
132 }
133 }
134
135 /// A builder used to construct new [`SerializerOptions`] structs.
136 pub struct SerializerOptionsBuilder {
137 options: SerializerOptions,
138 }
139
140 impl SerializerOptionsBuilder {
141 /// Set the value for [`SerializerOptions::is_human_readable`].
142 pub fn human_readable(mut self, value: impl Into<Option<bool>>) -> Self {
143 self.options.human_readable = value.into();
144 self
145 }
146
147 /// Consume this builder and produce a [`SerializerOptions`].
148 pub fn build(self) -> SerializerOptions {
149 self.options
150 }
151 }
152
153 impl Serializer {
154 /// Construct a new [`Serializer`].
155 #[allow(clippy::new_without_default)]
156 pub fn new() -> Serializer {
157 Serializer {
158 options: Default::default(),
159 }
160 }
161
162 /// Construct a new [`Serializer`] configured with the provided [`SerializerOptions`].
163 pub fn new_with_options(options: SerializerOptions) -> Self {
164 Serializer { options }
165 }
166 }
167
168 impl ser::Serializer for Serializer {
169 type Ok = Bson;
170 type Error = Error;
171
172 type SerializeSeq = ArraySerializer;
173 type SerializeTuple = TupleSerializer;
174 type SerializeTupleStruct = TupleStructSerializer;
175 type SerializeTupleVariant = TupleVariantSerializer;
176 type SerializeMap = MapSerializer;
177 type SerializeStruct = StructSerializer;
178 type SerializeStructVariant = StructVariantSerializer;
179
180 #[inline]
181 fn serialize_bool(self, value: bool) -> crate::ser::Result<Bson> {
182 Ok(Bson::Boolean(value))
183 }
184
185 #[inline]
186 fn serialize_i8(self, value: i8) -> crate::ser::Result<Bson> {
187 self.serialize_i32(value as i32)
188 }
189
190 #[inline]
191 fn serialize_u8(self, value: u8) -> crate::ser::Result<Bson> {
192 Ok(Bson::Int32(value as i32))
193 }
194
195 #[inline]
196 fn serialize_i16(self, value: i16) -> crate::ser::Result<Bson> {
197 self.serialize_i32(value as i32)
198 }
199
200 #[inline]
201 fn serialize_u16(self, value: u16) -> crate::ser::Result<Bson> {
202 Ok(Bson::Int32(value as i32))
203 }
204
205 #[inline]
206 fn serialize_i32(self, value: i32) -> crate::ser::Result<Bson> {
207 Ok(Bson::Int32(value))
208 }
209
210 #[inline]
211 fn serialize_u32(self, value: u32) -> crate::ser::Result<Bson> {
212 Ok(Bson::Int64(value as i64))
213 }
214
215 #[inline]
216 fn serialize_i64(self, value: i64) -> crate::ser::Result<Bson> {
217 Ok(Bson::Int64(value))
218 }
219
220 #[inline]
221 fn serialize_u64(self, value: u64) -> crate::ser::Result<Bson> {
222 use std::convert::TryFrom;
223
224 match i64::try_from(value) {
225 Ok(ivalue) => Ok(Bson::Int64(ivalue)),
226 Err(_) => Err(Error::UnsignedIntegerExceededRange(value)),
227 }
228 }
229
230 #[inline]
231 fn serialize_f32(self, value: f32) -> crate::ser::Result<Bson> {
232 self.serialize_f64(value as f64)
233 }
234
235 #[inline]
236 fn serialize_f64(self, value: f64) -> crate::ser::Result<Bson> {
237 Ok(Bson::Double(value))
238 }
239
240 #[inline]
241 fn serialize_char(self, value: char) -> crate::ser::Result<Bson> {
242 let mut s = String::new();
243 s.push(value);
244 self.serialize_str(&s)
245 }
246
247 #[inline]
248 fn serialize_str(self, value: &str) -> crate::ser::Result<Bson> {
249 Ok(Bson::String(value.to_string()))
250 }
251
252 fn serialize_bytes(self, value: &[u8]) -> crate::ser::Result<Bson> {
253 // let mut state = self.serialize_seq(Some(value.len()))?;
254 // for byte in value {
255 // state.serialize_element(byte)?;
256 // }
257 // state.end()
258 Ok(Bson::Binary(Binary {
259 subtype: BinarySubtype::Generic,
260 bytes: value.to_vec(),
261 }))
262 }
263
264 #[inline]
265 fn serialize_none(self) -> crate::ser::Result<Bson> {
266 self.serialize_unit()
267 }
268
269 #[inline]
270 fn serialize_some<V: ?Sized>(self, value: &V) -> crate::ser::Result<Bson>
271 where
272 V: Serialize,
273 {
274 value.serialize(self)
275 }
276
277 #[inline]
278 fn serialize_unit(self) -> crate::ser::Result<Bson> {
279 Ok(Bson::Null)
280 }
281
282 #[inline]
283 fn serialize_unit_struct(self, _name: &'static str) -> crate::ser::Result<Bson> {
284 self.serialize_unit()
285 }
286
287 #[inline]
288 fn serialize_unit_variant(
289 self,
290 _name: &'static str,
291 _variant_index: u32,
292 variant: &'static str,
293 ) -> crate::ser::Result<Bson> {
294 Ok(Bson::String(variant.to_string()))
295 }
296
297 #[inline]
298 fn serialize_newtype_struct<T: ?Sized>(
299 self,
300 name: &'static str,
301 value: &T,
302 ) -> crate::ser::Result<Bson>
303 where
304 T: Serialize,
305 {
306 match name {
307 UUID_NEWTYPE_NAME => {
308 let is_human_readable = self.is_human_readable();
309 match value.serialize(self)? {
310 Bson::String(s) if is_human_readable => {
311 // the serializer reports itself as human readable, so [`Uuid`] will
312 // serialize itself as a string.
313 let uuid = crate::Uuid::parse_str(s).map_err(Error::custom)?;
314 Ok(Bson::Binary(uuid.into()))
315 }
316 Bson::Binary(b) if !is_human_readable => Ok(Bson::Binary(Binary {
317 bytes: b.bytes,
318 subtype: BinarySubtype::Uuid,
319 })),
320 b => {
321 let expectation = if is_human_readable {
322 "a string"
323 } else {
324 "bytes"
325 };
326 Err(Error::custom(format!(
327 "expected UUID to be serialized as {} but got {:?} instead",
328 expectation, b
329 )))
330 }
331 }
332 }
333 // when in non-human-readable mode, raw document / raw array will serialize as bytes.
334 RAW_DOCUMENT_NEWTYPE | RAW_ARRAY_NEWTYPE if !self.is_human_readable() => match value
335 .serialize(self)?
336 {
337 Bson::Binary(b) => {
338 let doc = Document::from_reader(b.bytes.as_slice()).map_err(Error::custom)?;
339
340 if name == RAW_DOCUMENT_NEWTYPE {
341 Ok(Bson::Document(doc))
342 } else {
343 Ok(Bson::Array(doc.into_iter().map(|kvp| kvp.1).collect()))
344 }
345 }
346 b => Err(Error::custom(format!(
347 "expected raw document or array to be serialized as bytes but got {:?} instead",
348 b
349 ))),
350 },
351 _ => value.serialize(self),
352 }
353 }
354
355 #[inline]
356 fn serialize_newtype_variant<T: ?Sized>(
357 self,
358 _name: &'static str,
359 _variant_index: u32,
360 variant: &'static str,
361 value: &T,
362 ) -> crate::ser::Result<Bson>
363 where
364 T: Serialize,
365 {
366 let mut newtype_variant = Document::new();
367 newtype_variant.insert(variant, to_bson_with_options(value, self.options)?);
368 Ok(newtype_variant.into())
369 }
370
371 #[inline]
372 fn serialize_seq(self, len: Option<usize>) -> crate::ser::Result<Self::SerializeSeq> {
373 Ok(ArraySerializer {
374 inner: Array::with_capacity(len.unwrap_or(0)),
375 options: self.options,
376 })
377 }
378
379 #[inline]
380 fn serialize_tuple(self, len: usize) -> crate::ser::Result<Self::SerializeTuple> {
381 Ok(TupleSerializer {
382 inner: Array::with_capacity(len),
383 options: self.options,
384 })
385 }
386
387 #[inline]
388 fn serialize_tuple_struct(
389 self,
390 _name: &'static str,
391 len: usize,
392 ) -> crate::ser::Result<Self::SerializeTupleStruct> {
393 Ok(TupleStructSerializer {
394 inner: Array::with_capacity(len),
395 options: self.options,
396 })
397 }
398
399 #[inline]
400 fn serialize_tuple_variant(
401 self,
402 _name: &'static str,
403 _variant_index: u32,
404 variant: &'static str,
405 len: usize,
406 ) -> crate::ser::Result<Self::SerializeTupleVariant> {
407 Ok(TupleVariantSerializer {
408 inner: Array::with_capacity(len),
409 name: variant,
410 options: self.options,
411 })
412 }
413
414 #[inline]
415 fn serialize_map(self, _len: Option<usize>) -> crate::ser::Result<Self::SerializeMap> {
416 Ok(MapSerializer {
417 inner: Document::new(),
418 next_key: None,
419 options: self.options,
420 })
421 }
422
423 #[inline]
424 fn serialize_struct(
425 self,
426 _name: &'static str,
427 _len: usize,
428 ) -> crate::ser::Result<Self::SerializeStruct> {
429 Ok(StructSerializer {
430 inner: Document::new(),
431 options: self.options,
432 })
433 }
434
435 #[inline]
436 fn serialize_struct_variant(
437 self,
438 _name: &'static str,
439 _variant_index: u32,
440 variant: &'static str,
441 _len: usize,
442 ) -> crate::ser::Result<Self::SerializeStructVariant> {
443 Ok(StructVariantSerializer {
444 name: variant,
445 inner: Document::new(),
446 options: self.options,
447 })
448 }
449
450 fn is_human_readable(&self) -> bool {
451 self.options.human_readable.unwrap_or(true)
452 }
453 }
454
455 #[doc(hidden)]
456 pub struct ArraySerializer {
457 inner: Array,
458 options: SerializerOptions,
459 }
460
461 impl SerializeSeq for ArraySerializer {
462 type Ok = Bson;
463 type Error = Error;
464
465 fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> crate::ser::Result<()> {
466 self.inner
467 .push(to_bson_with_options(value, self.options.clone())?);
468 Ok(())
469 }
470
471 fn end(self) -> crate::ser::Result<Bson> {
472 Ok(Bson::Array(self.inner))
473 }
474 }
475
476 #[doc(hidden)]
477 pub struct TupleSerializer {
478 inner: Array,
479 options: SerializerOptions,
480 }
481
482 impl SerializeTuple for TupleSerializer {
483 type Ok = Bson;
484 type Error = Error;
485
486 fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> crate::ser::Result<()> {
487 self.inner
488 .push(to_bson_with_options(value, self.options.clone())?);
489 Ok(())
490 }
491
492 fn end(self) -> crate::ser::Result<Bson> {
493 Ok(Bson::Array(self.inner))
494 }
495 }
496
497 #[doc(hidden)]
498 pub struct TupleStructSerializer {
499 inner: Array,
500 options: SerializerOptions,
501 }
502
503 impl SerializeTupleStruct for TupleStructSerializer {
504 type Ok = Bson;
505 type Error = Error;
506
507 fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> crate::ser::Result<()> {
508 self.inner
509 .push(to_bson_with_options(value, self.options.clone())?);
510 Ok(())
511 }
512
513 fn end(self) -> crate::ser::Result<Bson> {
514 Ok(Bson::Array(self.inner))
515 }
516 }
517
518 #[doc(hidden)]
519 pub struct TupleVariantSerializer {
520 inner: Array,
521 name: &'static str,
522 options: SerializerOptions,
523 }
524
525 impl SerializeTupleVariant for TupleVariantSerializer {
526 type Ok = Bson;
527 type Error = Error;
528
529 fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> crate::ser::Result<()> {
530 self.inner
531 .push(to_bson_with_options(value, self.options.clone())?);
532 Ok(())
533 }
534
535 fn end(self) -> crate::ser::Result<Bson> {
536 let mut tuple_variant = Document::new();
537 tuple_variant.insert(self.name, self.inner);
538 Ok(tuple_variant.into())
539 }
540 }
541
542 #[doc(hidden)]
543 pub struct MapSerializer {
544 inner: Document,
545 next_key: Option<String>,
546 options: SerializerOptions,
547 }
548
549 impl SerializeMap for MapSerializer {
550 type Ok = Bson;
551 type Error = Error;
552
553 fn serialize_key<T: ?Sized + Serialize>(&mut self, key: &T) -> crate::ser::Result<()> {
554 self.next_key = match to_bson_with_options(&key, self.options.clone())? {
555 Bson::String(s) => Some(s),
556 other => return Err(Error::InvalidDocumentKey(other)),
557 };
558 Ok(())
559 }
560
561 fn serialize_value<T: ?Sized + Serialize>(&mut self, value: &T) -> crate::ser::Result<()> {
562 let key = self.next_key.take().unwrap_or_default();
563 self.inner
564 .insert(key, to_bson_with_options(&value, self.options.clone())?);
565 Ok(())
566 }
567
568 fn end(self) -> crate::ser::Result<Bson> {
569 Ok(Bson::from_extended_document(self.inner))
570 }
571 }
572
573 #[doc(hidden)]
574 pub struct StructSerializer {
575 inner: Document,
576 options: SerializerOptions,
577 }
578
579 impl SerializeStruct for StructSerializer {
580 type Ok = Bson;
581 type Error = Error;
582
583 fn serialize_field<T: ?Sized + Serialize>(
584 &mut self,
585 key: &'static str,
586 value: &T,
587 ) -> crate::ser::Result<()> {
588 self.inner
589 .insert(key, to_bson_with_options(value, self.options.clone())?);
590 Ok(())
591 }
592
593 fn end(self) -> crate::ser::Result<Bson> {
594 Ok(Bson::from_extended_document(self.inner))
595 }
596 }
597
598 #[doc(hidden)]
599 pub struct StructVariantSerializer {
600 inner: Document,
601 name: &'static str,
602 options: SerializerOptions,
603 }
604
605 impl SerializeStructVariant for StructVariantSerializer {
606 type Ok = Bson;
607 type Error = Error;
608
609 fn serialize_field<T: ?Sized + Serialize>(
610 &mut self,
611 key: &'static str,
612 value: &T,
613 ) -> crate::ser::Result<()> {
614 self.inner
615 .insert(key, to_bson_with_options(value, self.options.clone())?);
616 Ok(())
617 }
618
619 fn end(self) -> crate::ser::Result<Bson> {
620 let var = Bson::from_extended_document(self.inner);
621
622 let mut struct_variant = Document::new();
623 struct_variant.insert(self.name, var);
624
625 Ok(Bson::Document(struct_variant))
626 }
627 }
628
629 impl Serialize for Timestamp {
630 #[inline]
631 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
632 where
633 S: ser::Serializer,
634 {
635 let mut state = serializer.serialize_struct("$timestamp", 1)?;
636 let body = extjson::models::TimestampBody {
637 t: self.time,
638 i: self.increment,
639 };
640 state.serialize_field("$timestamp", &body)?;
641 state.end()
642 }
643 }
644
645 impl Serialize for Regex {
646 #[inline]
647 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
648 where
649 S: ser::Serializer,
650 {
651 let raw = RawRegexRef {
652 pattern: self.pattern.as_str(),
653 options: self.options.as_str(),
654 };
655 raw.serialize(serializer)
656 }
657 }
658
659 impl Serialize for JavaScriptCodeWithScope {
660 #[inline]
661 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
662 where
663 S: ser::Serializer,
664 {
665 let mut state = serializer.serialize_struct("$codeWithScope", 2)?;
666 state.serialize_field("$code", &self.code)?;
667 state.serialize_field("$scope", &self.scope)?;
668 state.end()
669 }
670 }
671
672 impl Serialize for Binary {
673 #[inline]
674 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
675 where
676 S: ser::Serializer,
677 {
678 if let BinarySubtype::Generic = self.subtype {
679 serializer.serialize_bytes(self.bytes.as_slice())
680 } else {
681 let mut state = serializer.serialize_struct("$binary", 1)?;
682 let body = extjson::models::BinaryBody {
683 base64: base64::encode(self.bytes.as_slice()),
684 subtype: hex::encode([self.subtype.into()]),
685 };
686 state.serialize_field("$binary", &body)?;
687 state.end()
688 }
689 }
690 }
691
692 impl Serialize for Decimal128 {
693 #[inline]
694 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
695 where
696 S: ser::Serializer,
697 {
698 if serializer.is_human_readable() {
699 let mut state = serializer.serialize_map(Some(1))?;
700 state.serialize_entry("$numberDecimal", &self.to_string())?;
701 state.end()
702 } else {
703 let mut state = serializer.serialize_struct("$numberDecimal", 1)?;
704 state.serialize_field("$numberDecimalBytes", serde_bytes::Bytes::new(&self.bytes))?;
705 state.end()
706 }
707 }
708 }
709
710 impl Serialize for DateTime {
711 #[inline]
712 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
713 where
714 S: ser::Serializer,
715 {
716 let mut state = serializer.serialize_struct("$date", 1)?;
717 let body = extjson::models::DateTimeBody::from_millis(self.timestamp_millis());
718 state.serialize_field("$date", &body)?;
719 state.end()
720 }
721 }
722
723 impl Serialize for DbPointer {
724 #[inline]
725 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
726 where
727 S: ser::Serializer,
728 {
729 let raw = RawDbPointerRef {
730 namespace: self.namespace.as_str(),
731 id: self.id,
732 };
733 raw.serialize(serializer)
734 }
735 }