Repository: pyfisch/cbor
Pull request #22 (2017-01-28 05:05:33)

Upgrade to serde 0.9


Patch:
diff --git a/.gitignore b/.gitignore
index a96cbeb..8880350 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,3 +2,5 @@ target
 Cargo.lock
 *.rs.bk
 tokamak.toml
+.idea
+*.iml
diff --git a/.travis.yml b/.travis.yml
index 04715ea..787a23b 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -10,7 +10,7 @@ rust:
 - nightly
 - beta
 - stable
-- 1.8.0
+- 1.13.0
 before_script:
 - |
   pip install 'travis-cargo<0.2' --user &&
diff --git a/Cargo.toml b/Cargo.toml
index 06fe35f..5a2ca62 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -10,9 +10,9 @@ description = "CBOR serialization and deserialization using serde."
 keywords = ["serde", "cbor", "serialization"]
 
 [dependencies]
-byteorder = "0.5"
-serde = "0.8.0"
-serde_macros = { version="0.8.0", optional=true }
+byteorder = "1.0"
+serde = "0.9.0"
+serde_derive = { version="0.9.0", optional=true }
 
 [features]
-unstable = ["serde_macros"]
+unstable = ["serde_derive"]
diff --git a/src/de.rs b/src/de.rs
index 5d51e20..b12ea5d 100644
--- a/src/de.rs
+++ b/src/de.rs
@@ -3,7 +3,7 @@
 use std::io::{self, Read};
 
 use byteorder::{BigEndian, ReadBytesExt};
-use serde::de::{self, EnumVisitor, Visitor, Deserialize};
+use serde::de::{self, Visitor, Deserialize, DeserializeSeed};
 use serde::bytes::ByteBuf;
 
 use super::error::{Error, Result};
@@ -13,7 +13,7 @@ const MAX_SEQ_LEN: u64 = 524288;
 macro_rules! forward_deserialize {
     ($($name:ident($($arg:ident: $ty:ty,)*);)*) => {
         $(#[inline]
-        fn $name<V: Visitor>(&mut self, $($arg: $ty,)* visitor: V) -> Result<V::Value> {
+        fn $name<V: Visitor>(self, $($arg: $ty,)* visitor: V) -> Result<V::Value> {
             self.deserialize(visitor)
         })*
     }
@@ -86,7 +86,7 @@ impl<R: Read> Deserializer<R> {
     }
 
     #[inline]
-    fn parse_uint<V: Visitor>(&mut self, first: u8, mut visitor: V) -> Result<V::Value> {
+    fn parse_uint<V: Visitor>(&mut self, first: u8, visitor: V) -> Result<V::Value> {
         match first & 0b000_11111 {
             n @ 0...23 => visitor.visit_u8(n),
             24 => visitor.visit_u8(try!(self.read_u8())),
@@ -98,7 +98,7 @@ impl<R: Read> Deserializer<R> {
     }
 
     #[inline]
-    fn parse_int<V: Visitor>(&mut self, first: u8, mut visitor: V) -> Result<V::Value> {
+    fn parse_int<V: Visitor>(&mut self, first: u8, visitor: V) -> Result<V::Value> {
         match first & 0b000_11111 {
             n @ 0...23 => visitor.visit_i8(-1 - n as i8),
             24 => visitor.visit_i16(-1 - try!(self.read_u8()) as i16),
@@ -110,7 +110,7 @@ impl<R: Read> Deserializer<R> {
     }
 
     #[inline]
-    fn parse_byte_buf<V: Visitor>(&mut self, first: u8, mut visitor: V) -> Result<V::Value> {
+    fn parse_byte_buf<V: Visitor>(&mut self, first: u8, visitor: V) -> Result<V::Value> {
         if let Some(n) = try!(self.parse_size_information(first)) {
             let mut buf = vec![0; n];
             try!(self.reader.read_exact(&mut buf));
@@ -118,7 +118,7 @@ impl<R: Read> Deserializer<R> {
         } else {
             let mut bytes = Vec::new();
             loop {
-                match ByteBuf::deserialize(self) {
+                match ByteBuf::deserialize(&mut *self) {
                     Ok(value) => bytes.append(&mut value.into()),
                     Err(Error::StopCode) => break,
                     Err(e) => return Err(e),
@@ -129,7 +129,7 @@ impl<R: Read> Deserializer<R> {
     }
 
     #[inline]
-    fn parse_string<V: Visitor>(&mut self, first: u8, mut visitor: V) -> Result<V::Value> {
+    fn parse_string<V: Visitor>(&mut self, first: u8, visitor: V) -> Result<V::Value> {
         if let Some(n) = try!(self.parse_size_information(first)) {
             let mut buf = vec![0; n];
             try!(self.reader.read_exact(&mut buf));
@@ -137,7 +137,7 @@ impl<R: Read> Deserializer<R> {
         } else {
             let mut string = String::new();
             loop {
-                match String::deserialize(self) {
+                match String::deserialize(&mut *self) {
                     Ok(value) => string.push_str(&value[..]),
                     Err(Error::StopCode) => break,
                     Err(e) => return Err(e),
@@ -148,13 +148,13 @@ impl<R: Read> Deserializer<R> {
     }
 
     #[inline]
-    fn parse_seq<V: Visitor>(&mut self, first: u8, mut visitor: V) -> Result<V::Value> {
+    fn parse_seq<V: Visitor>(&mut self, first: u8, visitor: V) -> Result<V::Value> {
         let n = try!(self.parse_size_information(first));
         visitor.visit_seq(CompositeVisitor::new(self, n.map(|x| x as usize)))
     }
 
     #[inline]
-    fn parse_map<V: Visitor>(&mut self, first: u8, mut visitor: V) -> Result<V::Value> {
+    fn parse_map<V: Visitor>(&mut self, first: u8, visitor: V) -> Result<V::Value> {
         let n = try!(self.parse_size_information(first));
         visitor.visit_map(CompositeVisitor::new(self, n.map(|x| x as usize)))
     }
@@ -167,7 +167,7 @@ impl<R: Read> Deserializer<R> {
     }
 
     #[inline]
-    fn parse_simple_value<V: Visitor>(&mut self, first: u8, mut visitor: V) -> Result<V::Value> {
+    fn parse_simple_value<V: Visitor>(&mut self, first: u8, visitor: V) -> Result<V::Value> {
         #[inline]
         fn decode_f16(half: u16) -> f32 {
             let exp: u16 = half >> 10 & 0x1f;
@@ -201,16 +201,14 @@ impl<R: Read> Deserializer<R> {
     }
 }
 
-impl<R: Read> de::Deserializer for Deserializer<R> {
+impl<'a, R: Read> de::Deserializer for &'a mut Deserializer<R> {
     type Error = Error;
     forward_deserialize!(
         deserialize_bool();
-        deserialize_isize();
         deserialize_i8();
         deserialize_i16();
         deserialize_i32();
         deserialize_i64();
-        deserialize_usize();
         deserialize_u8();
         deserialize_u16();
         deserialize_u32();
@@ -224,6 +222,7 @@ impl<R: Read> de::Deserializer for Deserializer<R> {
         deserialize_seq();
         deserialize_seq_fixed_size(_len: usize,);
         deserialize_bytes();
+        deserialize_byte_buf();
         deserialize_map();
         deserialize_unit_struct(_name: &'static str,);
         deserialize_tuple_struct(_name: &'static str, _len: usize,);
@@ -233,7 +232,7 @@ impl<R: Read> de::Deserializer for Deserializer<R> {
         deserialize_ignored_any();
     );
     #[inline]
-    fn deserialize<V: Visitor>(&mut self, visitor: V) -> Result<V::Value> {
+    fn deserialize<V: Visitor>(self, visitor: V) -> Result<V::Value> {
         if self.first.is_none() {
             self.first = Some(try!(self.read_u8()));
         }
@@ -243,7 +242,7 @@ impl<R: Read> de::Deserializer for Deserializer<R> {
     }
 
     #[inline]
-    fn deserialize_option<V: Visitor>(&mut self, mut visitor: V) -> Result<V::Value> {
+    fn deserialize_option<V: Visitor>(self, visitor: V) -> Result<V::Value> {
         self.first = Some(try!(self.read_u8()));
         if self.first == Some(0b111_10110) {
             self.first = None;
@@ -253,9 +252,9 @@ impl<R: Read> de::Deserializer for Deserializer<R> {
         }
     }
     #[inline]
-    fn deserialize_newtype_struct<V>(&mut self,
+    fn deserialize_newtype_struct<V>(self,
                                      _name: &'static str,
-                                     mut visitor: V)
+                                     visitor: V)
                                      -> Result<V::Value>
         where V: de::Visitor
     {
@@ -263,11 +262,11 @@ impl<R: Read> de::Deserializer for Deserializer<R> {
     }
 
     #[inline]
-    fn deserialize_enum<V: EnumVisitor>(&mut self,
-                                        _enum: &'static str,
-                                        _variants: &'static [&'static str],
-                                        mut visitor: V)
-                                        -> Result<V::Value> {
+    fn deserialize_enum<V: Visitor>(self,
+                                    _enum: &'static str,
+                                    _variants: &'static [&'static str],
+                                    visitor: V)
+                                    -> Result<V::Value> {
         let first = try!(self.read_u8());
         let items = match (first & 0b111_00000) >> 5 {
             3 => {
@@ -277,7 +276,7 @@ impl<R: Read> de::Deserializer for Deserializer<R> {
             4 => try!(self.parse_size_information(first)),
             _ => return Err(Error::Syntax),
         };
-        visitor.visit(CompositeVisitor::new(self, items))
+        visitor.visit_enum(CompositeVisitor::new(self, items))
     }
 }
 
@@ -302,13 +301,13 @@ impl<'a, R: 'a + Read> CompositeVisitor<'a, R> {
         }
     }
 
-    fn _visit<T: Deserialize>(&mut self) -> Result<Option<T>> {
+    fn _visit<T: DeserializeSeed>(&mut self, seed: T) -> Result<Option<T::Value>> {
         match self.items {
             Some(0) => return Ok(None),
             Some(ref mut n) => *n -= 1,
             _ => {}
         };
-        match Deserialize::deserialize(self.de) {
+        match seed.deserialize(&mut *self.de) {
             Ok(value) => Ok(Some(value)),
             Err(Error::StopCode) if self.items.is_none() => {
                 self.items = Some(0);
@@ -333,11 +332,8 @@ impl<'a, R: 'a + Read> CompositeVisitor<'a, R> {
 
 impl<'a, R: Read> de::SeqVisitor for CompositeVisitor<'a, R> {
     type Error = Error;
-    fn visit<T: Deserialize>(&mut self) -> Result<Option<T>> {
-        self._visit()
-    }
-    fn end(&mut self) -> Result<()> {
-        self._end()
+    fn visit_seed<T: DeserializeSeed>(&mut self, seed: T) -> Result<Option<T::Value>> {
+        self._visit(seed)
     }
     fn size_hint(&self) -> (usize, Option<usize>) {
         self._size_hint()
@@ -346,27 +342,33 @@ impl<'a, R: Read> de::SeqVisitor for CompositeVisitor<'a, R> {
 
 impl<'a, R: Read> de::MapVisitor for CompositeVisitor<'a, R> {
     type Error = Error;
-    fn visit_key<K: Deserialize>(&mut self) -> Result<Option<K>> {
-        self._visit()
-    }
-    fn visit_value<V: Deserialize>(&mut self) -> Result<V> {
-        Deserialize::deserialize(self.de)
+    fn visit_key_seed<K: DeserializeSeed>(&mut self, seed: K) -> Result<Option<K::Value>> {
+        self._visit(seed)
     }
-    fn end(&mut self) -> Result<()> {
-        self._end()
+    fn visit_value_seed<V: DeserializeSeed>(&mut self, seed: V) -> Result<V::Value> {
+        seed.deserialize(&mut *self.de)
     }
     fn size_hint(&self) -> (usize, Option<usize>) {
         self._size_hint()
     }
 }
 
-impl<'a, R: Read> de::VariantVisitor for CompositeVisitor<'a, R> {
+impl<'a, R: Read> de::EnumVisitor for CompositeVisitor<'a, R> {
     type Error = Error;
-    fn visit_variant<V: Deserialize>(&mut self) -> Result<V> {
-        Deserialize::deserialize(self.de)
+    type Variant = Self;
+
+    fn visit_variant_seed<V>(self, seed: V) -> Result<(V::Value, Self)>
+        where V: de::DeserializeSeed
+    {
+        let val = try!(seed.deserialize(&mut *self.de));
+        Ok((val, self))
     }
+}
+
+impl<'a, R: Read> de::VariantVisitor for CompositeVisitor<'a, R> {
+    type Error = Error;
 
-    fn visit_unit(&mut self) -> Result<()> {
+    fn visit_unit(self) -> Result<()> {
         if self.items == Some(0) {
             Ok(())
         } else {
@@ -374,11 +376,11 @@ impl<'a, R: Read> de::VariantVisitor for CompositeVisitor<'a, R> {
         }
     }
 
-    fn visit_newtype<T: Deserialize>(&mut self) -> Result<T> {
-        Deserialize::deserialize(self.de)
+    fn visit_newtype_seed<T: DeserializeSeed>(self, seed: T) -> Result<T::Value> {
+        seed.deserialize(self.de)
     }
 
-    fn visit_tuple<V: Visitor>(&mut self, len: usize, mut visitor: V) -> Result<V::Value> {
+    fn visit_tuple<V: Visitor>(self, len: usize, visitor: V) -> Result<V::Value> {
         if self.items.is_some() && self.items != Some(len + 1) {
             return Err(Error::Syntax);
         }
@@ -386,7 +388,7 @@ impl<'a, R: Read> de::VariantVisitor for CompositeVisitor<'a, R> {
         visitor.visit_seq(seq)
     }
 
-    fn visit_struct<V: Visitor>(&mut self,
+    fn visit_struct<V: Visitor>(self,
                                 _fields: &'static [&'static str],
                                 visitor: V)
                                 -> Result<V::Value> {
diff --git a/src/error.rs b/src/error.rs
index 34fd25e..780e906 100644
--- a/src/error.rs
+++ b/src/error.rs
@@ -76,18 +76,14 @@ impl From<FromUtf8Error> for Error {
 }
 
 impl de::Error for Error {
-    fn custom<T: Into<String>>(msg: T) -> Error {
-        Error::Custom(msg.into())
-    }
-
-    fn end_of_stream() -> Error {
-        Error::Eof
+    fn custom<T: fmt::Display>(msg: T) -> Error {
+        Error::Custom(msg.to_string())
     }
 }
 
 impl ser::Error for Error {
-    fn custom<T: Into<String>>(msg: T) -> Error {
-        Error::Custom(msg.into())
+    fn custom<T: fmt::Display>(msg: T) -> Error {
+        Error::Custom(msg.to_string())
     }
 }
 
diff --git a/src/ser.rs b/src/ser.rs
index e385260..b9bd8e8 100644
--- a/src/ser.rs
+++ b/src/ser.rs
@@ -3,7 +3,7 @@
 use std::io::Write;
 
 use byteorder::{BigEndian, WriteBytesExt};
-use serde::ser::{self, Serialize};
+use serde::ser::{self, Serialize, Serializer as SerdeSerializer};
 
 use {Error, Result};
 
@@ -89,13 +89,22 @@ impl<W: Write> Serializer<W> {
     }
 
     #[inline]
-    fn write_collection_start(&mut self, major: u8, len: Option<usize>) -> Result<CollectionState> {
+    fn write_collection_start(&mut self,
+                              major: u8,
+                              len: Option<usize>)
+                              -> Result<Compound<W, CollectionState>> {
         if let Some(len) = len {
             try!(self.write_type_u64(major, len as u64));
-            Ok(CollectionState::Fixed)
+            Ok(Compound {
+                ser: self,
+                state: CollectionState::Fixed,
+            })
         } else {
             try!(self.writer.write_u8(major << 5 | 31));
-            Ok(CollectionState::Indefinite)
+            Ok(Compound {
+                ser: self,
+                state: CollectionState::Indefinite,
+            })
         }
     }
 
@@ -108,36 +117,151 @@ impl<W: Write> Serializer<W> {
     }
 }
 
-/// A collection like an array or map may have a fixed or indefinite length.
+#[doc(hidden)]
 pub enum CollectionState {
-    /// Fixed collections end after all elements were serialized.
     Fixed,
-    /// Indefinite collections are terminated by a stop code after the last element.
     Indefinite,
 }
 
-/// Structs are record types. They are serialized as key value pairs.
-///
-/// The keys are either strings or indexes denoting the position in the struct.
-/// In `packed` serialization indexes are used to preserve space.
-///
-/// To keep track of the current index a counter is stored in this state.
+#[doc(hidden)]
 pub struct StructState {
     counter: usize,
 }
 
-impl<W: Write> ser::Serializer for Serializer<W> {
+#[doc(hidden)]
+pub struct Compound<'a, W: 'a + Write, S> {
+    ser: &'a mut Serializer<W>,
+    state: S,
+}
+
+impl<'a, W: Write> ser::SerializeSeq for Compound<'a, W, CollectionState> {
+    type Ok = ();
+    type Error = Error;
+
+    fn serialize_element<T: ?Sized + ser::Serialize>(&mut self, value: &T) -> Result<()> {
+        value.serialize(&mut *self.ser)
+    }
+
+    fn end(self) -> Result<()> {
+        self.ser.write_collection_end(self.state)
+    }
+}
+
+impl<'a, W: Write> ser::SerializeTuple for &'a mut Serializer<W> {
+    type Ok = ();
+    type Error = Error;
+
+    fn serialize_element<T: ?Sized + ser::Serialize>(&mut self, value: &T) -> Result<()> {
+        value.serialize(&mut **self)
+    }
+
+    fn end(self) -> Result<()> {
+        Ok(())
+    }
+}
+
+impl<'a, W: Write> ser::SerializeTupleStruct for &'a mut Serializer<W> {
+    type Ok = ();
+    type Error = Error;
+
+    fn serialize_field<T: ?Sized + ser::Serialize>(&mut self, value: &T) -> Result<()> {
+        value.serialize(&mut **self)
+    }
+
+    fn end(self) -> Result<()> {
+        Ok(())
+    }
+}
+
+impl<'a, W: Write> ser::SerializeTupleVariant for &'a mut Serializer<W> {
+    type Ok = ();
+    type Error = Error;
+
+    fn serialize_field<T: ?Sized + ser::Serialize>(&mut self, value: &T) -> Result<()> {
+        value.serialize(&mut **self)
+    }
+
+    fn end(self) -> Result<()> {
+        Ok(())
+    }
+}
+
+impl<'a, W: Write> ser::SerializeMap for Compound<'a, W, CollectionState> {
+    type Ok = ();
+    type Error = Error;
+
+    fn serialize_key<T: ?Sized + ser::Serialize>(&mut self, value: &T) -> Result<()> {
+        value.serialize(&mut *self.ser)
+    }
+
+    fn serialize_value<T: ?Sized + ser::Serialize>(&mut self, value: &T) -> Result<()> {
+        value.serialize(&mut *self.ser)
+    }
+
+    fn end(self) -> Result<()> {
+        self.ser.write_collection_end(self.state)
+    }
+}
+
+impl<'a, W: Write> ser::SerializeStruct for Compound<'a, W, StructState> {
+    type Ok = ();
+    type Error = Error;
+
+    fn serialize_field<T: ?Sized + ser::Serialize>(&mut self,
+                                                   key: &'static str,
+                                                   value: &T)
+                                                   -> Result<()> {
+        if !self.ser.packed {
+            try!(self.ser.serialize_str(key));
+        } else {
+            try!(self.ser.serialize_u64(self.state.counter as u64));
+        }
+        try!(value.serialize(&mut *self.ser));
+        self.state.counter += 1;
+        Ok(())
+    }
+
+    fn end(self) -> Result<()> {
+        Ok(())
+    }
+}
+
+impl<'a, W: Write> ser::SerializeStructVariant for Compound<'a, W, StructState> {
+    type Ok = ();
     type Error = Error;
-    type SeqState = CollectionState;
-    type TupleState = ();
-    type TupleStructState = ();
-    type TupleVariantState = ();
-    type MapState = CollectionState;
-    type StructState = StructState;
-    type StructVariantState = StructState;
+
+    fn serialize_field<T: ?Sized + ser::Serialize>(&mut self,
+                                                   key: &'static str,
+                                                   value: &T)
+                                                   -> Result<()> {
+        if !self.ser.packed {
+            try!(self.ser.serialize_str(key));
+        } else {
+            try!(self.ser.serialize_u64(self.state.counter as u64));
+        }
+        try!(value.serialize(&mut *self.ser));
+        self.state.counter += 1;
+        Ok(())
+    }
+
+    fn end(self) -> Result<()> {
+        Ok(())
+    }
+}
+
+impl<'a, W: Write> ser::Serializer for &'a mut Serializer<W> {
+    type Ok = ();
+    type Error = Error;
+    type SerializeSeq = Compound<'a, W, CollectionState>;
+    type SerializeTuple = &'a mut Serializer<W>;
+    type SerializeTupleStruct = &'a mut Serializer<W>;
+    type SerializeTupleVariant = &'a mut Serializer<W>;
+    type SerializeMap = Compound<'a, W, CollectionState>;
+    type SerializeStruct = Compound<'a, W, StructState>;
+    type SerializeStructVariant = Compound<'a, W, StructState>;
 
     #[inline]
-    fn serialize_bool(&mut self, v: bool) -> Result<()> {
+    fn serialize_bool(self, v: bool) -> Result<()> {
         self.writer
             .write_u8(match v {
                 false => 7 << 5 | 20,
@@ -147,12 +271,7 @@ impl<W: Write> ser::Serializer for Serializer<W> {
     }
 
     #[inline]
-    fn serialize_isize(&mut self, v: isize) -> Result<()> {
-        self.serialize_i64(v as i64)
-    }
-
-    #[inline]
-    fn serialize_i8(&mut self, v: i8) -> Result<()> {
+    fn serialize_i8(self, v: i8) -> Result<()> {
         if v < 0 {
             self.write_type_u8(1, -(v + 1) as u8)
         } else {
@@ -161,7 +280,7 @@ impl<W: Write> ser::Serializer for Serializer<W> {
     }
 
     #[inline]
-    fn serialize_i16(&mut self, v: i16) -> Result<()> {
+    fn serialize_i16(self, v: i16) -> Result<()> {
         if v < 0 {
             self.write_type_u16(1, -(v + 1) as u16)
         } else {
@@ -170,7 +289,7 @@ impl<W: Write> ser::Serializer for Serializer<W> {
     }
 
     #[inline]
-    fn serialize_i32(&mut self, v: i32) -> Result<()> {
+    fn serialize_i32(self, v: i32) -> Result<()> {
         if v < 0 {
             self.write_type_u32(1, -(v + 1) as u32)
         } else {
@@ -179,7 +298,7 @@ impl<W: Write> ser::Serializer for Serializer<W> {
     }
 
     #[inline]
-    fn serialize_i64(&mut self, v: i64) -> Result<()> {
+    fn serialize_i64(self, v: i64) -> Result<()> {
         if v < 0 {
             self.write_type_u64(1, -(v + 1) as u64)
         } else {
@@ -188,32 +307,27 @@ impl<W: Write> ser::Serializer for Serializer<W> {
     }
 
     #[inline]
-    fn serialize_usize(&mut self, v: usize) -> Result<()> {
-        self.serialize_u64(v as u64)
-    }
-
-    #[inline]
-    fn serialize_u8(&mut self, v: u8) -> Result<()> {
+    fn serialize_u8(self, v: u8) -> Result<()> {
         self.write_type_u8(0, v)
     }
 
     #[inline]
-    fn serialize_u16(&mut self, v: u16) -> Result<()> {
+    fn serialize_u16(self, v: u16) -> Result<()> {
         self.write_type_u16(0, v)
     }
 
     #[inline]
-    fn serialize_u32(&mut self, v: u32) -> Result<()> {
+    fn serialize_u32(self, v: u32) -> Result<()> {
         self.write_type_u32(0, v)
     }
 
     #[inline]
-    fn serialize_u64(&mut self, v: u64) -> Result<()> {
+    fn serialize_u64(self, v: u64) -> Result<()> {
         self.write_type_u64(0, v)
     }
 
     #[inline]
-    fn serialize_f32(&mut self, v: f32) -> Result<()> {
+    fn serialize_f32(self, v: f32) -> Result<()> {
         // TODO: Encode to f16
         if v.is_infinite() && v.is_sign_positive() {
                 self.writer.write_all(&[0xf9, 0x7c, 0x00])
@@ -230,7 +344,7 @@ impl<W: Write> ser::Serializer for Serializer<W> {
     }
 
     #[inline]
-    fn serialize_f64(&mut self, v: f64) -> Result<()> {
+    fn serialize_f64(self, v: f64) -> Result<()> {
         // TODO: Encode to f16
         if v.is_infinite() && v.is_sign_positive() {
                 self.writer.write_all(&[0xf9, 0x7c, 0x00])
@@ -251,7 +365,7 @@ impl<W: Write> ser::Serializer for Serializer<W> {
     }
 
     #[inline]
-    fn serialize_char(&mut self, v: char) -> Result<()> {
+    fn serialize_char(self, v: char) -> Result<()> {
         // TODO: Avoid allocation. rust-lang/rust#27784
         let mut s = String::new();
         s.push(v);
@@ -259,29 +373,39 @@ impl<W: Write> ser::Serializer for Serializer<W> {
     }
 
     #[inline]
-    fn serialize_str(&mut self, value: &str) -> Result<()> {
+    fn serialize_str(self, value: &str) -> Result<()> {
         try!(self.write_type_u64(3, value.len() as u64));
         self.writer.write_all(value.as_bytes()).map_err(From::from)
     }
 
     #[inline]
-    fn serialize_bytes(&mut self, value: &[u8]) -> Result<()> {
+    fn serialize_bytes(self, value: &[u8]) -> Result<()> {
         try!(self.write_type_u64(2, value.len() as u64));
         self.writer.write_all(value).map_err(From::from)
     }
 
     #[inline]
-    fn serialize_unit(&mut self) -> Result<()> {
+    fn serialize_none(self) -> Result<()> {
+        self.serialize_unit()
+    }
+
+    #[inline]
+    fn serialize_some<T: ?Sized + Serialize>(self, value: &T) -> Result<()> {
+        value.serialize(self)
+    }
+
+    #[inline]
+    fn serialize_unit(self) -> Result<()> {
         self.writer.write_u8(7 << 5 | 22).map_err(From::from)
     }
 
     #[inline]
-    fn serialize_unit_struct(&mut self, _name: &'static str) -> Result<()> {
+    fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
         self.serialize_unit()
     }
 
     #[inline]
-    fn serialize_unit_variant(&mut self,
+    fn serialize_unit_variant(self,
                               _name: &'static str,
                               variant_index: usize,
                               variant: &'static str)
@@ -289,205 +413,101 @@ impl<W: Write> ser::Serializer for Serializer<W> {
         if !self.packed {
             self.serialize_str(variant)
         } else {
-            self.serialize_usize(variant_index)
+            self.serialize_u64(variant_index as u64)
         }
     }
 
     #[inline]
-    fn serialize_newtype_struct<T: Serialize>(&mut self,
-                                              _name: &'static str,
-                                              value: T)
-                                              -> Result<()> {
+    fn serialize_newtype_struct<T: ?Sized + Serialize>(self,
+                                                       _name: &'static str,
+                                                       value: &T)
+                                                       -> Result<()> {
         value.serialize(self)
     }
 
     #[inline]
-    fn serialize_newtype_variant<T: Serialize>(&mut self,
-                                               name: &'static str,
-                                               variant_index: usize,
-                                               variant: &'static str,
-                                               value: T)
-                                               -> Result<()> {
+    fn serialize_newtype_variant<T: ?Sized + Serialize>(self,
+                                                        name: &'static str,
+                                                        variant_index: usize,
+                                                        variant: &'static str,
+                                                        value: &T)
+                                                        -> Result<()> {
         try!(self.writer.write_u8(4 << 5 | 2));
         try!(self.serialize_unit_variant(name, variant_index, variant));
         value.serialize(self)
     }
 
     #[inline]
-    fn serialize_none(&mut self) -> Result<()> {
-        self.serialize_unit()
-    }
-
-    #[inline]
-    fn serialize_some<T: Serialize>(&mut self, value: T) -> Result<()> {
-        value.serialize(self)
-    }
-
-    #[inline]
-    fn serialize_seq(&mut self, len: Option<usize>) -> Result<CollectionState> {
+    fn serialize_seq(self, len: Option<usize>) -> Result<Compound<'a, W, CollectionState>> {
         self.write_collection_start(4, len)
     }
 
     #[inline]
-    fn serialize_seq_elt<T: Serialize>(&mut self,
-                                       _state: &mut Self::SeqState,
-                                       value: T)
-                                       -> Result<()> {
-        value.serialize(self)
-    }
-
-    #[inline]
-    fn serialize_seq_end(&mut self, state: CollectionState) -> Result<()> {
-        self.write_collection_end(state)
-    }
-
-    #[inline]
-    fn serialize_seq_fixed_size(&mut self, size: usize) -> Result<CollectionState> {
+    fn serialize_seq_fixed_size(self, size: usize) -> Result<Compound<'a, W, CollectionState>> {
         self.serialize_seq(Some(size))
     }
 
     #[inline]
-    fn serialize_tuple(&mut self, len: usize) -> Result<()> {
-        self.write_type_u64(4, len as u64)
+    fn serialize_tuple(self, len: usize) -> Result<&'a mut Serializer<W>> {
+        try!(self.write_type_u64(4, len as u64));
+        Ok(self)
     }
 
     #[inline]
-    fn serialize_tuple_elt<T: Serialize>(&mut self, _state: &mut (), value: T) -> Result<()> {
-        value.serialize(self)
-    }
-
-    #[inline]
-    fn serialize_tuple_end(&mut self, _state: ()) -> Result<()> {
-        Ok(())
-    }
-
-    #[inline]
-    fn serialize_tuple_struct(&mut self, _name: &'static str, len: usize) -> Result<()> {
+    fn serialize_tuple_struct(self,
+                              _name: &'static str,
+                              len: usize)
+                              -> Result<&'a mut Serializer<W>> {
         self.serialize_tuple(len)
     }
 
     #[inline]
-    fn serialize_tuple_struct_elt<T: Serialize>(&mut self,
-                                                _state: &mut (),
-                                                value: T)
-                                                -> Result<()> {
-        value.serialize(self)
-    }
-
-    #[inline]
-    fn serialize_tuple_struct_end(&mut self, _state: ()) -> Result<()> {
-        Ok(())
-    }
-
-    #[inline]
-    fn serialize_tuple_variant(&mut self,
+    fn serialize_tuple_variant(self,
                                name: &'static str,
                                variant_index: usize,
                                variant: &'static str,
                                len: usize)
-                               -> Result<()> {
+                               -> Result<&'a mut Serializer<W>> {
         try!(self.write_type_u64(4, (len + 1) as u64));
-        self.serialize_unit_variant(name, variant_index, variant)
-    }
-
-    #[inline]
-    fn serialize_tuple_variant_elt<T: Serialize>(&mut self,
-                                                 _state: &mut (),
-                                                 value: T)
-                                                 -> Result<()> {
-        value.serialize(self)
-    }
-
-    #[inline]
-    fn serialize_tuple_variant_end(&mut self, _state: ()) -> Result<()> {
-        Ok(())
+        try!(self.serialize_unit_variant(name, variant_index, variant));
+        Ok(self)
     }
 
     #[inline]
-    fn serialize_map(&mut self, len: Option<usize>) -> Result<Self::MapState> {
+    fn serialize_map(self, len: Option<usize>) -> Result<Compound<'a, W, CollectionState>> {
         self.write_collection_start(5, len)
     }
 
     #[inline]
-    fn serialize_map_key<T: Serialize>(&mut self,
-                                       _state: &mut CollectionState,
-                                       key: T)
-                                       -> Result<()> {
-        key.serialize(self)
-    }
-
-    #[inline]
-    fn serialize_map_value<T: Serialize>(&mut self,
-                                         _state: &mut CollectionState,
-                                         value: T)
-                                         -> Result<()> {
-        value.serialize(self)
-    }
-
-    #[inline]
-    fn serialize_map_end(&mut self, state: CollectionState) -> Result<()> {
-        self.write_collection_end(state)
-    }
-
-    #[inline]
-    fn serialize_struct(&mut self, _name: &'static str, len: usize) -> Result<StructState> {
+    fn serialize_struct(self,
+                        _name: &'static str,
+                        len: usize)
+                        -> Result<Compound<'a, W, StructState>> {
         try!(self.write_type_u64(5, len as u64));
-        Ok(StructState { counter: 0 })
-    }
-
-    #[inline]
-    fn serialize_struct_elt<V: Serialize>(&mut self,
-                                          state: &mut StructState,
-                                          key: &'static str,
-                                          value: V)
-                                          -> Result<()> {
-        if !self.packed {
-            try!(self.serialize_str(key));
-        } else {
-            try!(self.serialize_usize(state.counter));
-        }
-        try!(value.serialize(self));
-        state.counter += 1;
-        Ok(())
-    }
-
-    #[inline]
-    fn serialize_struct_end(&mut self, _state: StructState) -> Result<()> {
-        Ok(())
+        Ok(Compound {
+            ser: self,
+            state: StructState {
+                counter: 0,
+            }
+        })
     }
 
     #[inline]
-    fn serialize_struct_variant(&mut self,
+    fn serialize_struct_variant(self,
                                 name: &'static str,
                                 variant_index: usize,
                                 variant: &'static str,
                                 len: usize)
-                                -> Result<StructState> {
+                                -> Result<Compound<'a, W, StructState>> {
         try!(self.writer.write_u8(4 << 5 | 2));
         try!(self.serialize_unit_variant(name, variant_index, variant));
         try!(self.write_type_u64(5, len as u64));
-        Ok(StructState { counter: 0 })
-    }
-
-    #[inline]
-    fn serialize_struct_variant_elt<V: Serialize>(&mut self,
-                                                  state: &mut StructState,
-                                                  key: &'static str,
-                                                  value: V)
-                                                  -> Result<()> {
-        if !self.packed {
-            try!(self.serialize_str(key));
-        } else {
-            try!(self.serialize_usize(state.counter));
-        }
-        try!(value.serialize(self));
-        state.counter += 1;
-        Ok(())
-    }
-
-    #[inline]
-    fn serialize_struct_variant_end(&mut self, _state: StructState) -> Result<()> {
-        Ok(())
+        Ok(Compound {
+            ser: self,
+            state: StructState {
+                counter: 0,
+            }
+        })
     }
 }
 
diff --git a/src/value.rs b/src/value.rs
index 38c4a42..daf0811 100644
--- a/src/value.rs
+++ b/src/value.rs
@@ -1,6 +1,7 @@
 //! CBOR values and keys.
 
 use std::collections::HashMap;
+use std::fmt;
 
 use serde::de::{self, SeqVisitor};
 use serde::ser;
@@ -213,7 +214,7 @@ impl Value {
 
 impl de::Deserialize for Value {
     #[inline]
-    fn deserialize<D>(deserializer: &mut D) -> Result<Value, D::Error>
+    fn deserialize<D>(deserializer: D) -> Result<Value, D::Error>
         where D: de::Deserializer
     {
         struct ValueVisitor;
@@ -221,70 +222,74 @@ impl de::Deserialize for Value {
         impl de::Visitor for ValueVisitor {
             type Value = Value;
 
+            fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+                fmt.write_str("any valid CBOR value")
+            }
+
             #[inline]
-            fn visit_str<E>(&mut self, value: &str) -> Result<Value, E>
+            fn visit_str<E>(self, value: &str) -> Result<Value, E>
                 where E: de::Error
             {
                 self.visit_string(String::from(value))
             }
 
             #[inline]
-            fn visit_string<E>(&mut self, value: String) -> Result<Value, E>
+            fn visit_string<E>(self, value: String) -> Result<Value, E>
                 where E: de::Error
             {
                 Ok(Value::String(value))
             }
             #[inline]
-            fn visit_bytes<E>(&mut self, v: &[u8]) -> Result<Self::Value, E>
+            fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
                 where E: de::Error
             {
                 self.visit_byte_buf(v.to_owned())
             }
 
             #[inline]
-            fn visit_byte_buf<E>(&mut self, v: Vec<u8>) -> Result<Self::Value, E>
+            fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
                 where E: de::Error
             {
                 Ok(Value::Bytes(v))
             }
 
             #[inline]
-            fn visit_u64<E>(&mut self, v: u64) -> Result<Self::Value, E>
+            fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
                 where E: de::Error
             {
                 Ok(Value::U64(v))
             }
 
             #[inline]
-            fn visit_i64<E>(&mut self, v: i64) -> Result<Self::Value, E>
+            fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
                 where E: de::Error
             {
                 Ok(Value::I64(v))
             }
 
             #[inline]
-            fn visit_bool<E>(&mut self, v: bool) -> Result<Self::Value, E>
+            fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
                 where E: de::Error
             {
                 Ok(Value::Bool(v))
             }
 
             #[inline]
-            fn visit_none<E>(&mut self) -> Result<Self::Value, E>
+            fn visit_none<E>(self) -> Result<Self::Value, E>
                 where E: de::Error
             {
                 self.visit_unit()
             }
 
             #[inline]
-            fn visit_unit<E>(&mut self) -> Result<Self::Value, E>
+            fn visit_unit<E>(self) -> Result<Self::Value, E>
                 where E: de::Error
             {
                 Ok(Value::Null)
             }
 
             #[inline]
-            fn visit_seq<V>(&mut self, visitor: V) -> Result<Self::Value, V::Error>
+            fn visit_seq<V>(self, visitor: V) -> Result<Self::Value, V::Error>
                 where V: SeqVisitor
             {
                 let values = try!(de::impls::VecVisitor::new().visit_seq(visitor));
@@ -292,7 +297,7 @@ impl de::Deserialize for Value {
             }
 
             #[inline]
-            fn visit_map<V>(&mut self, visitor: V) -> Result<Value, V::Error>
+            fn visit_map<V>(self, visitor: V) -> Result<Value, V::Error>
                 where V: de::MapVisitor
             {
                 let values = try!(de::impls::HashMapVisitor::new().visit_map(visitor));
@@ -300,7 +305,7 @@ impl de::Deserialize for Value {
             }
 
             #[inline]
-            fn visit_f64<E>(&mut self, v: f64) -> Result<Self::Value, E>
+            fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
                 where E: de::Error
             {
                 Ok(Value::F64(v))
@@ -314,7 +319,7 @@ impl de::Deserialize for Value {
 
 impl ser::Serialize for Value {
     #[inline]
-    fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
+    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
         where S: ser::Serializer
     {
         match *self {
@@ -448,7 +453,7 @@ impl ObjectKey {
 
 impl de::Deserialize for ObjectKey {
     #[inline]
-    fn deserialize<D>(deserializer: &mut D) -> Result<ObjectKey, D::Error>
+    fn deserialize<D>(deserializer: D) -> Result<ObjectKey, D::Error>
         where D: de::Deserializer
     {
         struct ObjectKeyVisitor;
@@ -456,63 +461,67 @@ impl de::Deserialize for ObjectKey {
         impl de::Visitor for ObjectKeyVisitor {
             type Value = ObjectKey;
 
+            fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+                fmt.write_str("any valid CBOR key")
+            }
+
             #[inline]
-            fn visit_str<E>(&mut self, value: &str) -> Result<Self::Value, E>
+            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
                 where E: de::Error
             {
                 self.visit_string(String::from(value))
             }
 
             #[inline]
-            fn visit_string<E>(&mut self, value: String) -> Result<Self::Value, E>
+            fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
                 where E: de::Error
             {
                 Ok(ObjectKey::String(value))
             }
             #[inline]
-            fn visit_bytes<E>(&mut self, v: &[u8]) -> Result<Self::Value, E>
+            fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
                 where E: de::Error
             {
                 self.visit_byte_buf(v.to_owned())
             }
 
             #[inline]
-            fn visit_byte_buf<E>(&mut self, v: Vec<u8>) -> Result<Self::Value, E>
+            fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
                 where E: de::Error
             {
                 Ok(ObjectKey::Bytes(v))
             }
 
             #[inline]
-            fn visit_u64<E>(&mut self, v: u64) -> Result<Self::Value, E>
+            fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
                 where E: de::Error
             {
                 Ok(ObjectKey::Integer(v as i64))
             }
 
             #[inline]
-            fn visit_i64<E>(&mut self, v: i64) -> Result<Self::Value, E>
+            fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
                 where E: de::Error
             {
                 Ok(ObjectKey::Integer(v))
             }
 
             #[inline]
-            fn visit_bool<E>(&mut self, v: bool) -> Result<Self::Value, E>
+            fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
                 where E: de::Error
             {
                 Ok(ObjectKey::Bool(v))
             }
 
             #[inline]
-            fn visit_none<E>(&mut self) -> Result<Self::Value, E>
+            fn visit_none<E>(self) -> Result<Self::Value, E>
                 where E: de::Error
             {
                 self.visit_unit()
             }
 
             #[inline]
-            fn visit_unit<E>(&mut self) -> Result<Self::Value, E>
+            fn visit_unit<E>(self) -> Result<Self::Value, E>
                 where E: de::Error
             {
                 Ok(ObjectKey::Null)
@@ -525,7 +534,7 @@ impl de::Deserialize for ObjectKey {
 
 impl ser::Serialize for ObjectKey {
     #[inline]
-    fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
+    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
         where S: ser::Serializer
     {
         match *self {


Test patch:
diff --git a/tests/enum.rs b/tests/enum.rs
index e991db6..53f63c6 100644
--- a/tests/enum.rs
+++ b/tests/enum.rs
@@ -1,11 +1,11 @@
 // All tests are only run if `unstable` is enabled.
 #![cfg(feature="unstable")]
-// Do not try to use features on stable.
-#![cfg_attr(feature="unstable", feature(custom_derive, plugin))]
-// Do not try to load the plugin if run on stable.
-#![cfg_attr(feature="unstable", plugin(serde_macros))]
 
 extern crate serde_cbor;
+
+#[macro_use]
+extern crate serde_derive;
+
 use serde_cbor::{from_slice, to_vec};
 
 #[derive(Debug,Serialize,Deserialize,PartialEq,Eq)]
@@ -30,8 +30,8 @@ fn test_enum() {
 #[repr(u16)]
 #[derive(Debug,Serialize,Deserialize,PartialEq,Eq)]
 enum ReprEnum {
-    A,  
-    B,  
+    A,
+    B,
 }
 
 #[derive(Debug,Serialize,Deserialize,PartialEq,Eq)]
diff --git a/tests/std_types.rs b/tests/std_types.rs
index b952e02..8fa09e8 100644
--- a/tests/std_types.rs
+++ b/tests/std_types.rs
@@ -1,11 +1,10 @@
-// Do not try to use features on stable.
-#![cfg_attr(feature="unstable", feature(custom_derive, plugin))]
-// Do not try to load the plugin if run on stable.
-#![cfg_attr(feature="unstable", plugin(serde_macros))]
-
 extern crate serde;
 extern crate serde_cbor;
 
+#[cfg(feature = "unstable")]
+#[macro_use]
+extern crate serde_derive;
+
 use std::u8;
 
 use serde::bytes::ByteBuf;
@@ -49,7 +48,7 @@ macro_rules! testcase {
         }
     }
 }
-            
+
 
 testcase!(test_bool_false, bool, false, "f4");
 testcase!(test_bool_true, bool, true, "f5");