diff --git a/serde/src/ser/impls.rs b/serde/src/ser/impls.rs index 5eb36c56..bb3308e9 100644 --- a/serde/src/ser/impls.rs +++ b/serde/src/ser/impls.rs @@ -568,8 +568,7 @@ macro_rules! serialize_map { use super::SerializeMap; let mut map = try!(serializer.serialize_map(Some(self.len()))); for (k, v) in self { - try!(map.serialize_key(k)); - try!(map.serialize_value(v)); + try!(map.serialize_entry(k, v)); } map.end() } diff --git a/serde/src/ser/mod.rs b/serde/src/ser/mod.rs index e4df61b4..af9880ef 100644 --- a/serde/src/ser/mod.rs +++ b/serde/src/ser/mod.rs @@ -546,8 +546,7 @@ pub trait Serializer { /// ```rust,ignore /// let mut map = serializer.serialize_map(Some(self.len()))?; /// for (k, v) in self { - /// map.serialize_key(k)?; - /// map.serialize_value(v)?; + /// map.serialize_entry(k, v)?; /// } /// map.end() /// ``` @@ -705,8 +704,7 @@ pub trait SerializeTupleVariant { /// ```rust,ignore /// let mut map = serializer.serialize_map(Some(self.len()))?; /// for (k, v) in self { -/// map.serialize_key(k)?; -/// map.serialize_value(v)?; +/// map.serialize_entry(k, v)?; /// } /// map.end() /// ``` @@ -723,6 +721,28 @@ pub trait SerializeMap { /// Serialize a map value. fn serialize_value(&mut self, value: &T) -> Result<(), Self::Error>; + /// Serialize a map entry consisting of a key and a value. + /// + /// Some `Serialize` types are not able to hold a key and value in memory at + /// the same time so `SerializeMap` implementations are required to support + /// `serialize_key` and `serialize_value` individually. The + /// `serialize_entry` method allows serializers to optimize for the case + /// where key and value are both available. `Serialize` implementations are + /// encouraged to use `serialize_entry` if possible. + /// + /// The default implementation delegates to `serialize_key` and + /// `serialize_value`. This is appropriate for serializers that do not care + /// about performance or are not able to optimize `serialize_entry` any + /// better than this. + fn serialize_entry( + &mut self, + key: &K, + value: &V, + ) -> Result<(), Self::Error> { + try!(self.serialize_key(key)); + self.serialize_value(value) + } + /// Finish serializing a map. fn end(self) -> Result; }