serde_with/content/
ser.rs

1//! Buffer for serializing data.
2//!
3//! This is a copy and improvement of the `serde` private type:
4//! <https://github.com/serde-rs/serde/blob/55a7cedd737278a9d75a2efd038c6f38b8c38bd6/serde/src/private/ser.rs#L338-L997>
5//! The code is very stable in the `serde` crate, so no maintainability problem is expected.
6//!
7//! Since the type is private we copy the type here.
8//! `serde` is licensed as MIT+Apache2, the same as this crate.
9//!
10//! This version carries improvements compared to `serde`'s version.
11//! The types support 128-bit integers, which is supported for all targets in Rust 1.40+.
12//! The [`ContentSerializer`] can also be configured to human readable or compact representation.
13
14use crate::prelude::*;
15
16pub(crate) enum Content {
17    Bool(bool),
18
19    U8(u8),
20    U16(u16),
21    U32(u32),
22    U64(u64),
23    U128(u128),
24
25    I8(i8),
26    I16(i16),
27    I32(i32),
28    I64(i64),
29    I128(i128),
30
31    F32(f32),
32    F64(f64),
33
34    Char(char),
35    String(String),
36    Bytes(Vec<u8>),
37
38    None,
39    Some(Box<Content>),
40
41    Unit,
42    UnitStruct(&'static str),
43    UnitVariant(&'static str, u32, &'static str),
44    NewtypeStruct(&'static str, Box<Content>),
45    NewtypeVariant(&'static str, u32, &'static str, Box<Content>),
46
47    Seq(Vec<Content>),
48    Tuple(Vec<Content>),
49    TupleStruct(&'static str, Vec<Content>),
50    TupleVariant(&'static str, u32, &'static str, Vec<Content>),
51    Map(Vec<(Content, Content)>),
52    Struct(&'static str, Vec<(&'static str, Content)>),
53    StructVariant(
54        &'static str,
55        u32,
56        &'static str,
57        Vec<(&'static str, Content)>,
58    ),
59}
60
61impl Content {
62    pub(crate) fn as_str(&self) -> Option<&str> {
63        match self {
64            Self::String(ref x) => Some(x),
65            Self::Bytes(x) => core::str::from_utf8(x).ok(),
66            _ => None,
67        }
68    }
69}
70
71impl Serialize for Content {
72    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
73    where
74        S: Serializer,
75    {
76        match *self {
77            Content::Bool(b) => serializer.serialize_bool(b),
78            Content::U8(u) => serializer.serialize_u8(u),
79            Content::U16(u) => serializer.serialize_u16(u),
80            Content::U32(u) => serializer.serialize_u32(u),
81            Content::U64(u) => serializer.serialize_u64(u),
82            Content::U128(u) => serializer.serialize_u128(u),
83            Content::I8(i) => serializer.serialize_i8(i),
84            Content::I16(i) => serializer.serialize_i16(i),
85            Content::I32(i) => serializer.serialize_i32(i),
86            Content::I64(i) => serializer.serialize_i64(i),
87            Content::I128(i) => serializer.serialize_i128(i),
88            Content::F32(f) => serializer.serialize_f32(f),
89            Content::F64(f) => serializer.serialize_f64(f),
90            Content::Char(c) => serializer.serialize_char(c),
91            Content::String(ref s) => serializer.serialize_str(s),
92            Content::Bytes(ref b) => serializer.serialize_bytes(b),
93            Content::None => serializer.serialize_none(),
94            Content::Some(ref c) => serializer.serialize_some(&**c),
95            Content::Unit => serializer.serialize_unit(),
96            Content::UnitStruct(n) => serializer.serialize_unit_struct(n),
97            Content::UnitVariant(n, i, v) => serializer.serialize_unit_variant(n, i, v),
98            Content::NewtypeStruct(n, ref c) => serializer.serialize_newtype_struct(n, &**c),
99            Content::NewtypeVariant(n, i, v, ref c) => {
100                serializer.serialize_newtype_variant(n, i, v, &**c)
101            }
102            Content::Seq(ref elements) => elements.serialize(serializer),
103            Content::Tuple(ref elements) => {
104                let mut tuple = serializer.serialize_tuple(elements.len())?;
105                for e in elements {
106                    tuple.serialize_element(e)?;
107                }
108                tuple.end()
109            }
110            Content::TupleStruct(n, ref fields) => {
111                let mut ts = serializer.serialize_tuple_struct(n, fields.len())?;
112                for f in fields {
113                    ts.serialize_field(f)?;
114                }
115                ts.end()
116            }
117            Content::TupleVariant(n, i, v, ref fields) => {
118                let mut tv = serializer.serialize_tuple_variant(n, i, v, fields.len())?;
119                for f in fields {
120                    tv.serialize_field(f)?;
121                }
122                tv.end()
123            }
124            Content::Map(ref entries) => {
125                let mut map = serializer.serialize_map(Some(entries.len()))?;
126                for (k, v) in entries {
127                    map.serialize_entry(k, v)?;
128                }
129                map.end()
130            }
131            Content::Struct(n, ref fields) => {
132                let mut s = serializer.serialize_struct(n, fields.len())?;
133                for (k, v) in fields {
134                    s.serialize_field(k, v)?;
135                }
136                s.end()
137            }
138            Content::StructVariant(n, i, v, ref fields) => {
139                let mut sv = serializer.serialize_struct_variant(n, i, v, fields.len())?;
140                for (k, v) in fields {
141                    sv.serialize_field(k, v)?;
142                }
143                sv.end()
144            }
145        }
146    }
147}
148
149pub(crate) struct ContentSerializer<E> {
150    is_human_readable: bool,
151    error: PhantomData<E>,
152}
153
154impl<E> ContentSerializer<E> {
155    pub(crate) fn new(is_human_readable: bool) -> Self {
156        ContentSerializer {
157            is_human_readable,
158            error: PhantomData,
159        }
160    }
161}
162
163impl<E> Default for ContentSerializer<E> {
164    fn default() -> Self {
165        Self::new(true)
166    }
167}
168
169impl<E> Serializer for ContentSerializer<E>
170where
171    E: SerError,
172{
173    type Ok = Content;
174    type Error = E;
175
176    type SerializeSeq = SeqSerialize<E>;
177    type SerializeTuple = TupleSerialize<E>;
178    type SerializeTupleStruct = TupleStructSerialize<E>;
179    type SerializeTupleVariant = TupleVariantSerialize<E>;
180    type SerializeMap = MapSerialize<E>;
181    type SerializeStruct = StructSerialize<E>;
182    type SerializeStructVariant = StructVariantSerialize<E>;
183
184    fn is_human_readable(&self) -> bool {
185        self.is_human_readable
186    }
187
188    fn serialize_bool(self, v: bool) -> Result<Content, E> {
189        Ok(Content::Bool(v))
190    }
191
192    fn serialize_i8(self, v: i8) -> Result<Content, E> {
193        Ok(Content::I8(v))
194    }
195
196    fn serialize_i16(self, v: i16) -> Result<Content, E> {
197        Ok(Content::I16(v))
198    }
199
200    fn serialize_i32(self, v: i32) -> Result<Content, E> {
201        Ok(Content::I32(v))
202    }
203
204    fn serialize_i64(self, v: i64) -> Result<Content, E> {
205        Ok(Content::I64(v))
206    }
207
208    fn serialize_i128(self, v: i128) -> Result<Content, E> {
209        Ok(Content::I128(v))
210    }
211
212    fn serialize_u8(self, v: u8) -> Result<Content, E> {
213        Ok(Content::U8(v))
214    }
215
216    fn serialize_u16(self, v: u16) -> Result<Content, E> {
217        Ok(Content::U16(v))
218    }
219
220    fn serialize_u32(self, v: u32) -> Result<Content, E> {
221        Ok(Content::U32(v))
222    }
223
224    fn serialize_u64(self, v: u64) -> Result<Content, E> {
225        Ok(Content::U64(v))
226    }
227
228    fn serialize_u128(self, v: u128) -> Result<Content, E> {
229        Ok(Content::U128(v))
230    }
231
232    fn serialize_f32(self, v: f32) -> Result<Content, E> {
233        Ok(Content::F32(v))
234    }
235
236    fn serialize_f64(self, v: f64) -> Result<Content, E> {
237        Ok(Content::F64(v))
238    }
239
240    fn serialize_char(self, v: char) -> Result<Content, E> {
241        Ok(Content::Char(v))
242    }
243
244    fn serialize_str(self, value: &str) -> Result<Content, E> {
245        Ok(Content::String(value.to_owned()))
246    }
247
248    fn serialize_bytes(self, value: &[u8]) -> Result<Content, E> {
249        Ok(Content::Bytes(value.to_owned()))
250    }
251
252    fn serialize_none(self) -> Result<Content, E> {
253        Ok(Content::None)
254    }
255
256    fn serialize_some<T>(self, value: &T) -> Result<Content, E>
257    where
258        T: Serialize + ?Sized,
259    {
260        Ok(Content::Some(Box::new(value.serialize(self)?)))
261    }
262
263    fn serialize_unit(self) -> Result<Content, E> {
264        Ok(Content::Unit)
265    }
266
267    fn serialize_unit_struct(self, name: &'static str) -> Result<Content, E> {
268        Ok(Content::UnitStruct(name))
269    }
270
271    fn serialize_unit_variant(
272        self,
273        name: &'static str,
274        variant_index: u32,
275        variant: &'static str,
276    ) -> Result<Content, E> {
277        Ok(Content::UnitVariant(name, variant_index, variant))
278    }
279
280    fn serialize_newtype_struct<T>(self, name: &'static str, value: &T) -> Result<Content, E>
281    where
282        T: Serialize + ?Sized,
283    {
284        Ok(Content::NewtypeStruct(
285            name,
286            Box::new(value.serialize(self)?),
287        ))
288    }
289
290    fn serialize_newtype_variant<T>(
291        self,
292        name: &'static str,
293        variant_index: u32,
294        variant: &'static str,
295        value: &T,
296    ) -> Result<Content, E>
297    where
298        T: Serialize + ?Sized,
299    {
300        Ok(Content::NewtypeVariant(
301            name,
302            variant_index,
303            variant,
304            Box::new(value.serialize(self)?),
305        ))
306    }
307
308    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, E> {
309        Ok(SeqSerialize {
310            is_human_readable: self.is_human_readable,
311            elements: Vec::with_capacity(len.unwrap_or(0)),
312            error: PhantomData,
313        })
314    }
315
316    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, E> {
317        Ok(TupleSerialize {
318            is_human_readable: self.is_human_readable,
319            elements: Vec::with_capacity(len),
320            error: PhantomData,
321        })
322    }
323
324    fn serialize_tuple_struct(
325        self,
326        name: &'static str,
327        len: usize,
328    ) -> Result<Self::SerializeTupleStruct, E> {
329        Ok(TupleStructSerialize {
330            is_human_readable: self.is_human_readable,
331            name,
332            fields: Vec::with_capacity(len),
333            error: PhantomData,
334        })
335    }
336
337    fn serialize_tuple_variant(
338        self,
339        name: &'static str,
340        variant_index: u32,
341        variant: &'static str,
342        len: usize,
343    ) -> Result<Self::SerializeTupleVariant, E> {
344        Ok(TupleVariantSerialize {
345            is_human_readable: self.is_human_readable,
346            name,
347            variant_index,
348            variant,
349            fields: Vec::with_capacity(len),
350            error: PhantomData,
351        })
352    }
353
354    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, E> {
355        Ok(MapSerialize {
356            is_human_readable: self.is_human_readable,
357            entries: Vec::with_capacity(len.unwrap_or(0)),
358            key: None,
359            error: PhantomData,
360        })
361    }
362
363    fn serialize_struct(self, name: &'static str, len: usize) -> Result<Self::SerializeStruct, E> {
364        Ok(StructSerialize {
365            is_human_readable: self.is_human_readable,
366            name,
367            fields: Vec::with_capacity(len),
368            error: PhantomData,
369        })
370    }
371
372    fn serialize_struct_variant(
373        self,
374        name: &'static str,
375        variant_index: u32,
376        variant: &'static str,
377        len: usize,
378    ) -> Result<Self::SerializeStructVariant, E> {
379        Ok(StructVariantSerialize {
380            is_human_readable: self.is_human_readable,
381            name,
382            variant_index,
383            variant,
384            fields: Vec::with_capacity(len),
385            error: PhantomData,
386        })
387    }
388}
389
390pub(crate) struct SeqSerialize<E> {
391    is_human_readable: bool,
392    elements: Vec<Content>,
393    error: PhantomData<E>,
394}
395
396impl<E> SerializeSeq for SeqSerialize<E>
397where
398    E: SerError,
399{
400    type Ok = Content;
401    type Error = E;
402
403    fn serialize_element<T>(&mut self, value: &T) -> Result<(), E>
404    where
405        T: Serialize + ?Sized,
406    {
407        let value = value.serialize(ContentSerializer::<E>::new(self.is_human_readable))?;
408        self.elements.push(value);
409        Ok(())
410    }
411
412    fn end(self) -> Result<Content, E> {
413        Ok(Content::Seq(self.elements))
414    }
415}
416
417pub(crate) struct TupleSerialize<E> {
418    is_human_readable: bool,
419    elements: Vec<Content>,
420    error: PhantomData<E>,
421}
422
423impl<E> SerializeTuple for TupleSerialize<E>
424where
425    E: SerError,
426{
427    type Ok = Content;
428    type Error = E;
429
430    fn serialize_element<T>(&mut self, value: &T) -> Result<(), E>
431    where
432        T: Serialize + ?Sized,
433    {
434        let value = value.serialize(ContentSerializer::<E>::new(self.is_human_readable))?;
435        self.elements.push(value);
436        Ok(())
437    }
438
439    fn end(self) -> Result<Content, E> {
440        Ok(Content::Tuple(self.elements))
441    }
442}
443
444pub(crate) struct TupleStructSerialize<E> {
445    is_human_readable: bool,
446    name: &'static str,
447    fields: Vec<Content>,
448    error: PhantomData<E>,
449}
450
451impl<E> SerializeTupleStruct for TupleStructSerialize<E>
452where
453    E: SerError,
454{
455    type Ok = Content;
456    type Error = E;
457
458    fn serialize_field<T>(&mut self, value: &T) -> Result<(), E>
459    where
460        T: Serialize + ?Sized,
461    {
462        let value = value.serialize(ContentSerializer::<E>::new(self.is_human_readable))?;
463        self.fields.push(value);
464        Ok(())
465    }
466
467    fn end(self) -> Result<Content, E> {
468        Ok(Content::TupleStruct(self.name, self.fields))
469    }
470}
471
472pub(crate) struct TupleVariantSerialize<E> {
473    is_human_readable: bool,
474    name: &'static str,
475    variant_index: u32,
476    variant: &'static str,
477    fields: Vec<Content>,
478    error: PhantomData<E>,
479}
480
481impl<E> SerializeTupleVariant for TupleVariantSerialize<E>
482where
483    E: SerError,
484{
485    type Ok = Content;
486    type Error = E;
487
488    fn serialize_field<T>(&mut self, value: &T) -> Result<(), E>
489    where
490        T: Serialize + ?Sized,
491    {
492        let value = value.serialize(ContentSerializer::<E>::new(self.is_human_readable))?;
493        self.fields.push(value);
494        Ok(())
495    }
496
497    fn end(self) -> Result<Content, E> {
498        Ok(Content::TupleVariant(
499            self.name,
500            self.variant_index,
501            self.variant,
502            self.fields,
503        ))
504    }
505}
506
507pub(crate) struct MapSerialize<E> {
508    is_human_readable: bool,
509    entries: Vec<(Content, Content)>,
510    key: Option<Content>,
511    error: PhantomData<E>,
512}
513
514impl<E> SerializeMap for MapSerialize<E>
515where
516    E: SerError,
517{
518    type Ok = Content;
519    type Error = E;
520
521    fn serialize_key<T>(&mut self, key: &T) -> Result<(), E>
522    where
523        T: Serialize + ?Sized,
524    {
525        let key = key.serialize(ContentSerializer::<E>::new(self.is_human_readable))?;
526        self.key = Some(key);
527        Ok(())
528    }
529
530    fn serialize_value<T>(&mut self, value: &T) -> Result<(), E>
531    where
532        T: Serialize + ?Sized,
533    {
534        let key = self
535            .key
536            .take()
537            .expect("serialize_value called before serialize_key");
538        let value = value.serialize(ContentSerializer::<E>::new(self.is_human_readable))?;
539        self.entries.push((key, value));
540        Ok(())
541    }
542
543    fn end(self) -> Result<Content, E> {
544        Ok(Content::Map(self.entries))
545    }
546
547    fn serialize_entry<K, V>(&mut self, key: &K, value: &V) -> Result<(), E>
548    where
549        K: Serialize + ?Sized,
550        V: Serialize + ?Sized,
551    {
552        let key = key.serialize(ContentSerializer::<E>::new(self.is_human_readable))?;
553        let value = value.serialize(ContentSerializer::<E>::new(self.is_human_readable))?;
554        self.entries.push((key, value));
555        Ok(())
556    }
557}
558
559pub(crate) struct StructSerialize<E> {
560    is_human_readable: bool,
561    name: &'static str,
562    fields: Vec<(&'static str, Content)>,
563    error: PhantomData<E>,
564}
565
566impl<E> SerializeStruct for StructSerialize<E>
567where
568    E: SerError,
569{
570    type Ok = Content;
571    type Error = E;
572
573    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), E>
574    where
575        T: Serialize + ?Sized,
576    {
577        let value = value.serialize(ContentSerializer::<E>::new(self.is_human_readable))?;
578        self.fields.push((key, value));
579        Ok(())
580    }
581
582    fn end(self) -> Result<Content, E> {
583        Ok(Content::Struct(self.name, self.fields))
584    }
585}
586
587pub(crate) struct StructVariantSerialize<E> {
588    is_human_readable: bool,
589    name: &'static str,
590    variant_index: u32,
591    variant: &'static str,
592    fields: Vec<(&'static str, Content)>,
593    error: PhantomData<E>,
594}
595
596impl<E> SerializeStructVariant for StructVariantSerialize<E>
597where
598    E: SerError,
599{
600    type Ok = Content;
601    type Error = E;
602
603    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), E>
604    where
605        T: Serialize + ?Sized,
606    {
607        let value = value.serialize(ContentSerializer::<E>::new(self.is_human_readable))?;
608        self.fields.push((key, value));
609        Ok(())
610    }
611
612    fn end(self) -> Result<Content, E> {
613        Ok(Content::StructVariant(
614            self.name,
615            self.variant_index,
616            self.variant,
617            self.fields,
618        ))
619    }
620}