Skip to main content

deser_core/ser/
serializer.rs

1use crate::error::Error;
2use crate::ser::{Serialize, SerializeDriver, SerializeRef};
3
4/// Serializes values into an output.
5///
6/// This is implemented by the serializers of the data formats (for instance
7/// `deser_json::Serializer`) and by other destinations of values (like the
8/// value type of `deser-value`).  A serializer holds its output, every call
9/// serializes a value into it.  Serializers implement
10/// [`drive`](Self::drive) which receives the events of a value from a
11/// driver.  The provided methods create the driver:
12///
13/// * [`serialize`](Self::serialize) serializes a value.
14/// * [`serialize_with`](Self::serialize_with) serializes a value and allows
15///   configuring the driver first, for instance to add
16///   [`Layer`](crate::ser::Layer)s.
17///
18/// ```
19/// use deser::ser::{SerializeDriver, Serializer};
20/// use deser::{Atom, Error, ErrorKind, Event};
21///
22/// /// A format which writes sequences of numbers comma separated.
23/// struct Numbers(String);
24///
25/// impl Serializer for Numbers {
26///     fn drive(
27///         &mut self,
28///         driver: &mut SerializeDriver<'_>,
29///     ) -> Result<(), Error> {
30///         driver.drive(|event, _state| {
31///             match event {
32///                 Event::Atom(Atom::U64(value)) => {
33///                     if !self.0.is_empty() {
34///                         self.0.push_str(", ");
35///                     }
36///                     self.0.push_str(&value.to_string());
37///                 }
38///                 Event::SeqStart(_) | Event::SeqEnd => {}
39///                 _ => {
40///                     return Err(Error::new(
41///                         ErrorKind::UnsupportedType,
42///                         "not a number",
43///                     ));
44///                 }
45///             }
46///             Ok(())
47///         })
48///     }
49/// }
50///
51/// let mut numbers = Numbers(String::new());
52/// numbers.serialize(&vec![1u64, 2, 3]).unwrap();
53/// assert_eq!(numbers.0, "1, 2, 3");
54/// ```
55pub trait Serializer {
56    /// Receives the events of a value from the driver and writes them into
57    /// the output.
58    fn drive(&mut self, driver: &mut SerializeDriver<'_>) -> Result<(), Error>;
59
60    /// Serializes a value.
61    fn serialize<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error>
62    where
63        Self: Sized,
64    {
65        self.drive(&mut SerializeDriver::new(&value))
66    }
67
68    /// Serializes a value with a configured driver.
69    ///
70    /// The callback is invoked with the driver before the value is
71    /// serialized, for instance to add [`Layer`](crate::ser::Layer)s.
72    fn serialize_with<T, F>(&mut self, value: &T, setup: F) -> Result<(), Error>
73    where
74        T: Serialize + ?Sized,
75        F: FnOnce(&mut SerializeDriver<'_>),
76        Self: Sized,
77    {
78        let mut driver = SerializeDriver::new(&value);
79        setup(&mut driver);
80        self.drive(&mut driver)
81    }
82
83    /// Serializes the value of a reference.
84    ///
85    /// This is like [`serialize`](Self::serialize) but not generic.
86    fn serialize_ref(&mut self, value: SerializeRef<'_>) -> Result<(), Error> {
87        self.drive(&mut SerializeDriver::from_ref(value))
88    }
89}
90
91impl<S: Serializer + ?Sized> Serializer for &mut S {
92    fn drive(&mut self, driver: &mut SerializeDriver<'_>) -> Result<(), Error> {
93        (**self).drive(driver)
94    }
95}