Coverage Report

Created: 2025-07-02 06:18

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