pub trait Serializer {
// Required method
fn drive(&mut self, driver: &mut SerializeDriver<'_>) -> Result<(), Error>;
// Provided methods
fn serialize<T: Serialize + ?Sized>(
&mut self,
value: &T,
) -> Result<(), Error>
where Self: Sized { ... }
fn serialize_with<T, F>(&mut self, value: &T, setup: F) -> Result<(), Error>
where T: Serialize + ?Sized,
F: FnOnce(&mut SerializeDriver<'_>),
Self: Sized { ... }
fn serialize_ref(&mut self, value: SerializeRef<'_>) -> Result<(), Error> { ... }
}Expand description
Serializes values into an output.
This is implemented by the serializers of the data formats (for instance
deser_json::Serializer) and by other destinations of values (like the
value type of deser-value). A serializer holds its output, every call
serializes a value into it. Serializers implement
drive which receives the events of a value from a
driver. The provided methods create the driver:
serializeserializes a value.serialize_withserializes a value and allows configuring the driver first, for instance to addLayers.
use deser::ser::{SerializeDriver, Serializer};
use deser::{Atom, Error, ErrorKind, Event};
/// A format which writes sequences of numbers comma separated.
struct Numbers(String);
impl Serializer for Numbers {
fn drive(
&mut self,
driver: &mut SerializeDriver<'_>,
) -> Result<(), Error> {
driver.drive(|event, _state| {
match event {
Event::Atom(Atom::U64(value)) => {
if !self.0.is_empty() {
self.0.push_str(", ");
}
self.0.push_str(&value.to_string());
}
Event::SeqStart(_) | Event::SeqEnd => {}
_ => {
return Err(Error::new(
ErrorKind::UnsupportedType,
"not a number",
));
}
}
Ok(())
})
}
}
let mut numbers = Numbers(String::new());
numbers.serialize(&vec![1u64, 2, 3]).unwrap();
assert_eq!(numbers.0, "1, 2, 3");Required Methods§
Provided Methods§
Sourcefn serialize<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error>where
Self: Sized,
fn serialize<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error>where
Self: Sized,
Serializes a value.
Sourcefn serialize_with<T, F>(&mut self, value: &T, setup: F) -> Result<(), Error>
fn serialize_with<T, F>(&mut self, value: &T, setup: F) -> Result<(), Error>
Serializes a value with a configured driver.
The callback is invoked with the driver before the value is
serialized, for instance to add Layers.
Sourcefn serialize_ref(&mut self, value: SerializeRef<'_>) -> Result<(), Error>
fn serialize_ref(&mut self, value: SerializeRef<'_>) -> Result<(), Error>
Serializes the value of a reference.
This is like serialize but not generic.
Dyn Compatibility§
This trait is dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".
Implementations on Foreign Types§
Source§impl<S: Serializer + ?Sized> Serializer for &mut S
impl<S: Serializer + ?Sized> Serializer for &mut S
Implementors§
impl<W: Write, S: StreamSerializer> Serializer for Writer<W, S>
io only.Serializes values and writes them, like Writer::write.