diff --git a/README.md b/README.md index 04873ff3..3c136b84 100644 --- a/README.md +++ b/README.md @@ -356,11 +356,8 @@ impl serde::Serialize for i32 { ``` As you can see it's pretty simple. More complex types like `BTreeMap` need to -pass a -[MapVisitor](http://serde-rs.github.io/serde/serde/serde/ser/trait.MapVisitor.html) -to the -[Serializer](http://serde-rs.github.io/serde/serde/serde/ser/trait.Serializer.html) -in order to walk through the type: +use a multi-step process (init, elements, end) in order to walk through the +type: ```rust,ignore impl Serialize for BTreeMap @@ -371,55 +368,17 @@ impl Serialize for BTreeMap fn serialize(&self, serializer: &mut S) -> Result<(), S::Error> where S: Serializer, { - serializer.serialize_map(MapIteratorVisitor::new(self.iter(), Some(self.len()))) - } -} - -pub struct MapIteratorVisitor { - iter: Iter, - len: Option, -} - -impl MapIteratorVisitor - where Iter: Iterator -{ - #[inline] - pub fn new(iter: Iter, len: Option) -> MapIteratorVisitor { - MapIteratorVisitor { - iter: iter, - len: len, + let mut state = try!(serializer.serialize_map(Some(self.len()))); + for (k, v) in self { + try!(serializer.serialize_map_elt(&mut state, k, v)); } - } -} - -impl MapVisitor for MapIteratorVisitor - where K: Serialize, - V: Serialize, - I: Iterator, -{ - #[inline] - fn visit(&mut self, serializer: &mut S) -> Result, S::Error> - where S: Serializer, - { - match self.iter.next() { - Some((key, value)) => { - let value = try!(serializer.serialize_map_elt(key, value)); - Ok(Some(value)) - } - None => Ok(None) - } - } - - #[inline] - fn len(&self) -> Option { - self.len + serializer.serialize_map_end(state) } } ``` Serializing structs follow this same pattern. In fact, structs are represented -as a named map. Its visitor uses a simple state machine to iterate through all -the fields: +as a named map, with a known length. ```rust extern crate serde;