Trait SerializeMap
trait SerializeMap
Returned from Serializer::serialize_map.
Example use
# use std::marker::PhantomData;
#
# struct HashMap<K, V>(PhantomData<K>, PhantomData<V>);
#
# impl<K, V> HashMap<K, V> {
# fn len(&self) -> usize {
# unimplemented!()
# }
# }
#
# impl<'a, K, V> IntoIterator for &'a HashMap<K, V> {
# type Item = (&'a K, &'a V);
# type IntoIter = Box<dyn Iterator<Item = (&'a K, &'a V)>>;
#
# fn into_iter(self) -> Self::IntoIter {
# unimplemented!()
# }
# }
#
use serde::ser::{Serialize, SerializeMap, Serializer};
impl<K, V> Serialize for HashMap<K, V>
where
K: Serialize,
V: Serialize,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut map = serializer.serialize_map(Some(self.len()))?;
for (k, v) in self {
map.serialize_entry(k, v)?;
}
map.end()
}
}
Example implementation
The example data format presented on the website demonstrates an
implementation of SerializeMap for a basic JSON data format.
Associated Types
type OkMust match the
Oktype of ourSerializer.type Error: TraitBound { trait_: Path { path: "Error", id: Id(220), args: None }, generic_params: [], modifier: None }Must match the
Errortype of ourSerializer.
Required Methods
fn serialize_key<T>(self: &mut Self, key: &T) -> Result<(), <Self as >::Error> where T: ?Sized + SerializeSerialize a map key.
If possible,
Serializeimplementations are encouraged to useserialize_entryinstead as it may be implemented more efficiently in some formats compared to a pair of calls toserialize_keyandserialize_value.fn serialize_value<T>(self: &mut Self, value: &T) -> Result<(), <Self as >::Error> where T: ?Sized + SerializeSerialize a map value.
Panics
Calling
serialize_valuebeforeserialize_keyis incorrect and is allowed to panic or produce bogus results.fn end(self: Self) -> Result<<Self as >::Ok, <Self as >::Error>Finish serializing a map.
Provided Methods
fn serialize_entry<K, V>(self: &mut Self, key: &K, value: &V) -> Result<(), <Self as >::Error> where K: ?Sized + Serialize, V: ?Sized + SerializeSerialize a map entry consisting of a key and a value.
Some
Serializetypes are not able to hold a key and value in memory at the same time soSerializeMapimplementations are required to supportserialize_keyandserialize_valueindividually. Theserialize_entrymethod allows serializers to optimize for the case where key and value are both available.Serializeimplementations are encouraged to useserialize_entryif possible.The default implementation delegates to
serialize_keyandserialize_value. This is appropriate for serializers that do not care about performance or are not able to optimizeserialize_entryany better than this.
Implementors
impl<Ok, Error> SerializeMap for Impossible<Ok, Error>