pub struct Serializer { /* private fields */ }Expand description
Serializes values into Values.
This is a Serializer which builds a value
from the events of a serialized value. It’s what to_value uses, use
it directly to configure the serialization, for instance to add layers.
Every call to serialize adds a value:
use deser::ser::{Layer, Next};
use deser::{Atom, Error, Event};
use deser_value::{Serializer, value};
/// Writes all numbers as strings.
struct NumbersAsStrings;
impl Layer for NumbersAsStrings {
fn event(
&mut self,
event: Event<'_>,
next: &mut Next<'_>,
) -> Result<(), Error> {
match event {
Event::Atom(Atom::U64(value)) => {
next.emit(value.to_string().into())
}
event => next.emit(event),
}
}
}
let mut serializer = Serializer::new();
serializer.serialize(&true).unwrap();
serializer
.serialize_with(&vec![1u64, 2], |driver| {
driver.push_layer(NumbersAsStrings)
})
.unwrap();
assert_eq!(serializer.finish(), [value!(true), value!(["1", "2"])]);The event data of the serialized values (such as formatting hints) is captured in the meta data of the values.
Implementations§
Source§impl Serializer
impl Serializer
Sourcepub fn new() -> Serializer
pub fn new() -> Serializer
Creates a serializer.
Sourcepub fn serialize<T: Serialize + ?Sized>(
&mut self,
value: &T,
) -> Result<(), Error>
pub fn serialize<T: Serialize + ?Sized>( &mut self, value: &T, ) -> Result<(), Error>
Serializes a value.
If the value fails to serialize, nothing is added.
Sourcepub fn serialize_with<F, T: Serialize + ?Sized>(
&mut self,
value: &T,
setup: F,
) -> Result<(), Error>where
F: FnOnce(&mut SerializeDriver<'_>),
pub fn serialize_with<F, T: Serialize + ?Sized>(
&mut self,
value: &T,
setup: F,
) -> Result<(), Error>where
F: FnOnce(&mut SerializeDriver<'_>),
Serializes a value with a configured driver.
The callback is invoked with the driver before the value is
serialized, for instance to add Layers.
Sourcepub fn set_context(&mut self, context: Context)
pub fn set_context(&mut self, context: Context)
Sets the context the values are serialized in.
The values of the context are the defaults of the extension values
of the state (see Context). A context set
on the driver (for instance in the setup callback of serialize_with)
takes precedence.