deser_core/ser/serializer.rs
1use crate::error::Error;
2use crate::ser::{Serialize, SerializeDriver};
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(&mut self, value: &dyn Serialize) -> Result<(), Error> {
62 self.drive(&mut SerializeDriver::new(value))
63 }
64
65 /// Serializes a value with a configured driver.
66 ///
67 /// The callback is invoked with the driver before the value is
68 /// serialized, for instance to add [`Layer`](crate::ser::Layer)s.
69 fn serialize_with<F>(&mut self, value: &dyn Serialize, setup: F) -> Result<(), Error>
70 where
71 F: FnOnce(&mut SerializeDriver<'_>),
72 Self: Sized,
73 {
74 let mut driver = SerializeDriver::new(value);
75 setup(&mut driver);
76 self.drive(&mut driver)
77 }
78}
79
80impl<S: Serializer + ?Sized> Serializer for &mut S {
81 fn drive(&mut self, driver: &mut SerializeDriver<'_>) -> Result<(), Error> {
82 (**self).drive(driver)
83 }
84}