Repository: mongodb/bson-rust (language: rust)

Issue:
add to_object method for Bson
Before , user cannot directly convert bson to bussiness object ,but this is easy to do using the method `to_object` .

Add rustc-serialize/serde Encoder/Decoder implementation
It would be nice to have a suitable Encoder/Decoder (or Serializer/Deserializer) implementation for `Bson` type in order to automatically serialize serializable types to BSON.



Discussion / hints:
I am not sure this is the best way to do this. Maybe we could have an `Encoder` and `Decoder` that impl `rustc_serialize::Encoder` and `rustc_serialize::Decoder` instead of converting it to `Json` and then decode it to the object.

cc @kyeah 

Yes, I think doing two conversions is a bit roundabout and takes away from one of BSON's advantages, which is its encoding and decoding efficiency. A Bson `Encoder` and `Decoder` would be ideal to convert it directly, although this is a bit more involved.

@zonyitoo Yes, it's better.

I think #16 solves this same issue.

I think we can close this one since #16 has been merged.

I believe this and #16 solve different issues: #16 provides easy access to inner bson values, while this is converting arbitrary user-defined structs into Bson documents and vice versa.

Ah right. In that something on top of https://github.com/serde-rs/serde seems like a good idea.

Sounds promising. But I don't have time to implement it recently, so I should mark it as "enhancement".

BTW, I am happy to receive a PR. :P


Fix patch:
diff --git a/Cargo.toml b/Cargo.toml
index 56b7df94..9821b58c 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -17,4 +17,9 @@ libc = "0.1"
 rand = "0.3"
 rust-crypto = "0.2.31"
 rustc-serialize = "0.3"
+serde = "~0.6.1"
 time = "0.1"
+
+[dependencies.num]
+version = "~0.1.27"
+default-features = false
\ No newline at end of file
diff --git a/src/bson.rs b/src/bson.rs
index a1a98630..20d42c52 100644
--- a/src/bson.rs
+++ b/src/bson.rs
@@ -23,13 +23,14 @@
 
 use std::fmt::{Display, Error, Formatter};
 
-use chrono::{DateTime, UTC};
+use chrono::{DateTime, Timelike, UTC};
+use chrono::offset::TimeZone;
 use rustc_serialize::json;
-use rustc_serialize::hex::ToHex;
+use rustc_serialize::hex::{FromHex, ToHex};
 
+use oid;
 use ordered::OrderedDocument;
 use spec::{ElementType, BinarySubtype};
-use oid;
 
 /// Possible BSON value types.
 #[derive(Debug,Clone,PartialEq)]
@@ -244,15 +245,19 @@ impl Bson {
             &Bson::Null => json::Json::Null,
             &Bson::RegExp(ref pat, ref opt) => {
                 let mut re = json::Object::new();
-                re.insert("pattern".to_owned(), json::Json::String(pat.clone()));
-                re.insert("options".to_owned(), json::Json::String(opt.clone()));
+                re.insert("$regex".to_owned(), json::Json::String(pat.clone()));
+                re.insert("$options".to_owned(), json::Json::String(opt.clone()));
 
                 json::Json::Object(re)
             },
-            &Bson::JavaScriptCode(ref code) => json::Json::String(code.clone()),
+            &Bson::JavaScriptCode(ref code) => {
+                let mut obj = json::Object::new();
+                obj.insert("$code".to_owned(), json::Json::String(code.clone()));
+                json::Json::Object(obj)
+            },
             &Bson::JavaScriptCodeWithScope(ref code, ref scope) => {
                 let mut obj = json::Object::new();
-                obj.insert("code".to_owned(), json::Json::String(code.clone()));
+                obj.insert("$code".to_owned(), json::Json::String(code.clone()));
 
                 let scope_obj =
                     scope.iter().map(|(k, v)| (k.clone(), v.to_json())).collect();
@@ -263,17 +268,38 @@ impl Bson {
             },
             &Bson::I32(v) => json::Json::I64(v as i64),
             &Bson::I64(v) => json::Json::I64(v),
-            &Bson::TimeStamp(v) => json::Json::I64(v),
+            &Bson::TimeStamp(v) => {
+                let time = v >> 32;
+                let inc = v & 0x0000FFFF;
+
+                let mut obj = json::Object::new();
+                obj.insert("t".to_owned(), json::Json::I64(time));
+                obj.insert("i".to_owned(), json::Json::I64(inc));
+
+                json::Json::Object(obj)
+            },
             &Bson::Binary(t, ref v) => {
                 let mut obj = json::Object::new();
                 let tval: u8 = From::from(t);
                 obj.insert("type".to_owned(), json::Json::I64(tval as i64));
-                obj.insert("data".to_owned(), json::Json::String(v.to_hex()));
+                obj.insert("$binary".to_owned(), json::Json::String(v.to_hex()));
 
                 json::Json::Object(obj)
             },
-            &Bson::ObjectId(ref v) => json::Json::String(v.bytes().to_hex()),
-            &Bson::UtcDatetime(ref v) => json::Json::String(v.to_string()),
+            &Bson::ObjectId(ref v) => {
+                let mut obj = json::Object::new();
+                obj.insert("$oid".to_owned(), json::Json::String(v.to_string()));
+
+                json::Json::Object(obj)
+            },
+            &Bson::UtcDatetime(ref v) => {
+                let mut obj = json::Object::new();
+                let mut inner = json::Object::new();
+                inner.insert("$numberLong".to_owned(), json::Json::I64((v.timestamp() * 1000) + 
+                                                                       (v.nanosecond() / 1000000) as i64));
+                obj.insert("$date".to_owned(), json::Json::Object(inner));
+                json::Json::Object(obj)
+            }
         }
     }
 
@@ -286,8 +312,102 @@ impl Bson {
             &json::Json::String(ref x) => Bson::String(x.clone()),
             &json::Json::Boolean(x) => Bson::Boolean(x),
             &json::Json::Array(ref x) => Bson::Array(x.iter().map(Bson::from_json).collect()),
-            &json::Json::Object(ref x) => Bson::Document(x.iter().map(|(k, v)| (k.clone(), Bson::from_json(v))).collect()),
+            &json::Json::Object(ref x) => Bson::from_extended_document(
+                x.iter().map(|(k, v)| (k.clone(), Bson::from_json(v))).collect()),
             &json::Json::Null => Bson::Null,
         }
     }
+
+    pub fn to_extended_document(&self) -> Document {
+        match *self {
+            Bson::RegExp(ref pat, ref opt) => {
+                doc! {
+                    "$regex" => (pat.clone()),
+                    "$options" => (opt.clone())
+                }
+            }
+            Bson::JavaScriptCode(ref code) => {
+                doc! {
+                    "$code" => (code.clone())
+                }
+            }
+            Bson::JavaScriptCodeWithScope(ref code, ref scope) => {
+                doc! {
+                    "$code" => (code.clone()),
+                    "$scope" => (scope.clone())
+                }
+            }
+            Bson::TimeStamp(v) => {
+                let time = (v >> 32) as i32;
+                let inc = (v & 0xFFFFFFFF) as i32;
+
+                doc! {
+                    "t" => time,
+                    "i" => inc
+                }
+            }
+            Bson::Binary(t, ref v) => {
+                let tval: u8 = From::from(t);
+                doc! {
+                    "$binary" => (v.to_hex()),
+                    "type" => (tval as i64)
+                }
+            }
+            Bson::ObjectId(ref v) => {
+                doc! {
+                    "$oid" => (v.to_string())
+                }
+            }
+            Bson::UtcDatetime(ref v) => {
+                doc! {
+                    "$date" => {
+                        "$numberLong" => ((v.timestamp() * 1000) + (v.nanosecond() / 1000000) as i64)
+                    }
+                }
+            }
+            _ => panic!("Attempted conversion of invalid data type: {}", self),
+        }
+    }
+
+    pub fn from_extended_document(values: Document) -> Bson {
+        if values.len() == 2 {
+            if let (Ok(pat), Ok(opt)) = (values.get_str("$regex"), 
+                                         values.get_str("$options")) {
+                return Bson::RegExp(pat.to_owned(), opt.to_owned());
+
+            } else if let (Ok(code), Ok(scope)) = (values.get_str("$code"),
+                                                   values.get_document("$scope")) {
+                return Bson::JavaScriptCodeWithScope(code.to_owned(), scope.to_owned());
+
+            } else if let (Ok(t), Ok(i)) = (values.get_i32("t"),
+                                            values.get_i32("i")) {
+                let timestamp = ((t as i64) << 32) + (i as i64);
+                return Bson::TimeStamp(timestamp);
+
+            } else if let (Ok(t), Ok(i)) = (values.get_i64("t"),
+                                            values.get_i64("i")) {
+                let timestamp = (t << 32) + i;
+                return Bson::TimeStamp(timestamp);
+
+            } else if let (Ok(hex), Ok(t)) = (values.get_str("$binary"),
+                                              values.get_i64("type")) {
+                let ttype = t as u8;
+                return Bson::Binary(From::from(ttype), hex.from_hex().unwrap());
+            }
+
+        } else if values.len() == 1 {
+            if let Ok(code) = values.get_str("$code") {
+                return Bson::JavaScriptCode(code.to_owned());
+
+            } else if let Ok(hex) = values.get_str("$oid") {
+                return Bson::ObjectId(oid::ObjectId::with_string(hex).unwrap());
+
+            } else if let Ok(long) = values.get_document("$date")
+                                           .and_then(|inner| inner.get_i64("$numberLong")) {
+                return Bson::UtcDatetime(UTC.timestamp(long / 1000, (long % 1000) as u32 * 1000000));
+            }
+        }
+        
+        Bson::Document(values)
+    }
 }
diff --git a/src/decoder/error.rs b/src/decoder/error.rs
new file mode 100644
index 00000000..b34c984e
--- /dev/null
+++ b/src/decoder/error.rs
@@ -0,0 +1,102 @@
+use std::{io, error, fmt, str};
+use byteorder;
+use serde::de;
+
+/// Possible errors that can arise during decoding.
+#[derive(Debug)]
+pub enum DecoderError {
+    IoError(io::Error),
+    Utf8Error(str::Utf8Error),
+    UnrecognizedElementType(u8),
+    InvalidArrayKey(usize, String),
+    // A field was expected, but none was found.
+    ExpectedField(&'static str),
+    // An unexpected field was found.
+    UnknownField(String),
+    // There was an error with the syntactical structure of the BSON.
+    SyntaxError,
+    // The end of the BSON input was reached too soon.
+    EndOfStream,
+}
+
+impl From<io::Error> for DecoderError {
+    fn from(err: io::Error) -> DecoderError {
+        DecoderError::IoError(err)
+    }
+}
+
+impl From<str::Utf8Error> for DecoderError {
+    fn from(err: str::Utf8Error) -> DecoderError {
+        DecoderError::Utf8Error(err)
+    }
+}
+
+impl From<byteorder::Error> for DecoderError {
+    fn from(err: byteorder::Error) -> DecoderError {
+        DecoderError::IoError(From::from(err))
+    }
+}
+
+impl fmt::Display for DecoderError {
+    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+        match *self {
+            DecoderError::IoError(ref inner) => inner.fmt(fmt),
+            DecoderError::Utf8Error(ref inner) => inner.fmt(fmt),
+            DecoderError::UnrecognizedElementType(tag) => {
+                write!(fmt, "unrecognized element type `{}`", tag)
+            }
+            DecoderError::InvalidArrayKey(ref want, ref got) => {
+                write!(fmt, "invalid array key: expected `{}`, got `{}`", want, got)
+            }
+            DecoderError::ExpectedField(field_type) => {
+                write!(fmt, "expected a field of type `{}`", field_type)
+            }
+            DecoderError::UnknownField(ref field) => write!(fmt, "unknown field `{}`", field),
+            DecoderError::SyntaxError => write!(fmt, "syntax error"),
+            DecoderError::EndOfStream => write!(fmt, "end of stream"),
+        }
+    }
+}
+
+impl error::Error for DecoderError {
+    fn description(&self) -> &str {
+        match *self {
+            DecoderError::IoError(ref inner) => inner.description(),
+            DecoderError::Utf8Error(ref inner) => inner.description(),
+            DecoderError::UnrecognizedElementType(_) => "unrecognized element type",
+            DecoderError::InvalidArrayKey(_, _) => "invalid array key",
+            DecoderError::ExpectedField(_) => "expected a field",
+            DecoderError::UnknownField(_) => "found an unknown field",
+            DecoderError::SyntaxError => "syntax error",
+            DecoderError::EndOfStream => "end of stream",
+        }
+    }
+    fn cause(&self) -> Option<&error::Error> {
+        match *self {
+            DecoderError::IoError(ref inner) => Some(inner),
+            DecoderError::Utf8Error(ref inner) => Some(inner),
+            _ => None
+        }
+    }
+}
+
+impl de::Error for DecoderError {
+    fn syntax(_: &str) -> DecoderError {
+        DecoderError::SyntaxError
+    }
+
+    fn end_of_stream() -> DecoderError {
+        DecoderError::EndOfStream
+    }
+
+    fn unknown_field(field: &str) -> DecoderError {
+        DecoderError::UnknownField(String::from(field))
+    }
+
+    fn missing_field(field: &'static str) -> DecoderError {
+        DecoderError::ExpectedField(field)
+    }
+}
+
+/// Alias for `Result<T, DecoderError>`.
+pub type DecoderResult<T> = Result<T, DecoderError>;
diff --git a/src/decoder.rs b/src/decoder/mod.rs
similarity index 72%
rename from src/decoder.rs
rename to src/decoder/mod.rs
index d23e5d16..af50e558 100644
--- a/src/decoder.rs
+++ b/src/decoder/mod.rs
@@ -21,10 +21,16 @@
 
 //! Decoder
 
-use std::io::{self, Read};
-use std::{str, error, fmt};
+mod error;
+mod serde;
 
-use byteorder::{self, LittleEndian, ReadBytesExt};
+pub use self::error::{DecoderError, DecoderResult};
+pub use self::serde::Decoder;
+
+use std::io::Read;
+use std::str;
+
+use byteorder::{LittleEndian, ReadBytesExt};
 use chrono::{UTC};
 use chrono::offset::TimeZone;
 
@@ -32,68 +38,7 @@ use spec::{self, BinarySubtype};
 use bson::{Bson, Array, Document};
 use oid;
 
-/// Possible errors that can arise during decoding.
-#[derive(Debug)]
-pub enum DecoderError {
-    IoError(io::Error),
-    Utf8Error(str::Utf8Error),
-    UnrecognizedElementType(u8),
-    InvalidArrayKey(usize, String)
-}
-
-impl From<io::Error> for DecoderError {
-    fn from(err: io::Error) -> DecoderError {
-        DecoderError::IoError(err)
-    }
-}
-
-impl From<str::Utf8Error> for DecoderError {
-    fn from(err: str::Utf8Error) -> DecoderError {
-        DecoderError::Utf8Error(err)
-    }
-}
-
-impl From<byteorder::Error> for DecoderError {
-    fn from(err: byteorder::Error) -> DecoderError {
-        DecoderError::IoError(From::from(err))
-    }
-}
-
-impl fmt::Display for DecoderError {
-    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
-        match self {
-            &DecoderError::IoError(ref inner) => inner.fmt(fmt),
-            &DecoderError::Utf8Error(ref inner) => inner.fmt(fmt),
-            &DecoderError::UnrecognizedElementType(tag) => {
-                write!(fmt, "unrecognized element type `{}`", tag)
-            }
-            &DecoderError::InvalidArrayKey(ref want, ref got) => {
-                write!(fmt, "invalid array key: expected `{}`, got `{}`", want, got)
-            }
-        }
-    }
-}
-
-impl error::Error for DecoderError {
-    fn description(&self) -> &str {
-        match self {
-            &DecoderError::IoError(ref inner) => inner.description(),
-            &DecoderError::Utf8Error(ref inner) => inner.description(),
-            &DecoderError::UnrecognizedElementType(_) => "unrecognized element type",
-            &DecoderError::InvalidArrayKey(_, _) => "invalid array key"
-        }
-    }
-    fn cause(&self) -> Option<&error::Error> {
-        match self {
-            &DecoderError::IoError(ref inner) => Some(inner),
-            &DecoderError::Utf8Error(ref inner) => Some(inner),
-            _ => None
-        }
-    }
-}
-
-/// Alias for `Result<T, DecoderError>`.
-pub type DecoderResult<T> = Result<T, DecoderError>;
+use serde::de::Deserialize;
 
 fn read_string<R: Read + ?Sized>(reader: &mut R) -> DecoderResult<String> {
     let len = try!(reader.read_i32::<LittleEndian>());
@@ -226,3 +171,11 @@ fn decode_bson<R: Read + ?Sized>(reader: &mut R, tag: u8) -> DecoderResult<Bson>
         None => Err(DecoderError::UnrecognizedElementType(tag))
     }
 }
+
+/// Decode a BSON `Value` into a `T` Deserializable.
+pub fn from_bson<T>(bson: Bson) -> DecoderResult<T>
+    where T: Deserialize
+{
+    let mut de = Decoder::new(bson);
+    Deserialize::deserialize(&mut de)
+}
diff --git a/src/decoder/serde.rs b/src/decoder/serde.rs
new file mode 100644
index 00000000..bd8f1aaa
--- /dev/null
+++ b/src/decoder/serde.rs
@@ -0,0 +1,455 @@
+use std::vec;
+
+use serde::de::{self, Deserialize, Deserializer, Visitor,
+                EnumVisitor, MapVisitor, SeqVisitor, VariantVisitor};
+
+use bson::Bson;
+use oid::ObjectId;
+use ordered::{OrderedDocument, OrderedDocumentIntoIterator};
+use super::error::{DecoderError, DecoderResult};
+
+pub struct BsonVisitor;
+
+
+impl Deserialize for ObjectId {
+    fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
+        where D: Deserializer,
+    {
+        deserializer.visit_map(BsonVisitor)
+            .and_then(|bson| if let Bson::ObjectId(oid) = bson {
+                Ok(oid)
+            } else {
+                Err(de::Error::syntax(&format!("expected objectId extended document, found {}", bson)))
+            })
+    }
+}
+
+impl Deserialize for OrderedDocument {
+    /// Deserialize this value given this `Deserializer`.
+    fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
+        where D: Deserializer,
+    {
+        deserializer.visit_map(BsonVisitor)
+            .and_then(|bson| if let Bson::Document(doc) = bson {
+                Ok(doc)
+            } else {
+                Err(de::Error::syntax(&format!("expected document, found extended JSON data type: {}", bson)))
+            })
+    }
+}
+
+impl Deserialize for Bson {
+    #[inline]
+    fn deserialize<D>(deserializer: &mut D) -> Result<Bson, D::Error>
+        where D: Deserializer,
+    {
+        deserializer.visit(BsonVisitor)
+    }
+}
+
+impl Visitor for BsonVisitor {
+    type Value = Bson;
+    
+    #[inline]
+    fn visit_bool<E>(&mut self, value: bool) -> Result<Bson, E> {
+        Ok(Bson::Boolean(value))
+    }
+
+    #[inline]
+    fn visit_i8<E>(&mut self, value: i8) -> Result<Bson, E> {
+        Ok(Bson::I32(value as i32))
+    }
+
+
+    #[inline]
+    fn visit_i16<E>(&mut self, value: i16) -> Result<Bson, E> {
+        Ok(Bson::I32(value as i32))
+    }
+
+    
+    #[inline]
+    fn visit_i32<E>(&mut self, value: i32) -> Result<Bson, E> {
+        Ok(Bson::I32(value))
+    }
+
+    #[inline]
+    fn visit_i64<E>(&mut self, value: i64) -> Result<Bson, E> {
+        Ok(Bson::I64(value))
+    }
+    
+    #[inline]
+    fn visit_u64<E>(&mut self, value: u64) -> Result<Bson, E> {
+        Ok(Bson::I64(value as i64))
+    }
+    
+    #[inline]
+    fn visit_f64<E>(&mut self, value: f64) -> Result<Bson, E> {
+        Ok(Bson::FloatingPoint(value))
+    }
+    
+    #[inline]
+    fn visit_str<E>(&mut self, value: &str) -> Result<Bson, E>
+        where E: de::Error
+    {
+        self.visit_string(String::from(value))
+    }
+    
+    #[inline]
+    fn visit_string<E>(&mut self, value: String) -> Result<Bson, E> {
+        Ok(Bson::String(value))
+    }
+    
+    #[inline]
+    fn visit_none<E>(&mut self) -> Result<Bson, E> {
+        Ok(Bson::Null)
+    }
+    
+    #[inline]
+    fn visit_some<D>(&mut self, deserializer: &mut D) -> Result<Bson, D::Error>
+        where D: Deserializer,
+    {
+        de::Deserialize::deserialize(deserializer)
+    }
+    
+    #[inline]
+    fn visit_unit<E>(&mut self) -> Result<Bson, E> {
+        Ok(Bson::Null)
+    }
+    
+    #[inline]
+    fn visit_seq<V>(&mut self, visitor: V) -> Result<Bson, V::Error>
+        where V: SeqVisitor,
+    {
+        let values = try!(de::impls::VecVisitor::new().visit_seq(visitor));
+        Ok(Bson::Array(values))
+    }
+    
+    #[inline]
+    fn visit_map<V>(&mut self, visitor: V) -> Result<Bson, V::Error>
+        where V: MapVisitor,
+    {
+        let values = try!(de::impls::BTreeMapVisitor::new().visit_map(visitor));
+        Ok(Bson::from_extended_document(values.into()))
+    }
+}
+
+pub struct Decoder {
+    value: Option<Bson>,
+}
+
+impl Decoder {
+    pub fn new(value: Bson) -> Decoder {
+        Decoder {
+            value: Some(value),
+        }
+    }
+}
+
+impl Deserializer for Decoder {
+    type Error = DecoderError;
+
+    #[inline]
+    fn visit<V>(&mut self, mut visitor: V) -> DecoderResult<V::Value>
+        where V: Visitor,
+    {
+        let value = match self.value.take() {
+            Some(value) => value,
+            None => { return Err(de::Error::end_of_stream()); }
+        };
+
+        match value {
+            Bson::FloatingPoint(v) => visitor.visit_f64(v),
+            Bson::String(v) => visitor.visit_string(v),
+            Bson::Array(v) => {
+                let len = v.len();
+                visitor.visit_seq(SeqDecoder {
+                    de: self,
+                    iter: v.into_iter(),
+                    len: len,
+                })
+            }
+            Bson::Document(v) => {
+                let len = v.len();
+                visitor.visit_map(MapDecoder {
+                    de: self,
+                    iter: v.into_iter(),
+                    value: None,
+                    len: len,
+                })
+            }
+            Bson::Boolean(v) => visitor.visit_bool(v),
+            Bson::Null => visitor.visit_unit(),
+            Bson::I32(v) => visitor.visit_i32(v),
+            Bson::I64(v) => visitor.visit_i64(v),
+            _ => {
+                let doc = value.to_extended_document();
+                let len = doc.len();
+                visitor.visit_map(MapDecoder {
+                    de: self,
+                    iter: doc.into_iter(),
+                    value: None,
+                    len: len,
+                })
+            }
+        }
+    }
+
+    #[inline]
+    fn visit_option<V>(&mut self, mut visitor: V) -> DecoderResult<V::Value>
+        where V: Visitor,
+    {
+        match self.value {
+            Some(Bson::Null) => visitor.visit_none(),
+            Some(_) => visitor.visit_some(self),
+            None => Err(de::Error::end_of_stream()),
+        }
+    }
+
+    #[inline]
+    fn visit_enum<V>(&mut self,
+                     _name: &str,
+                     _variants: &'static [&'static str],
+                     mut visitor: V) -> DecoderResult<V::Value>
+        where V: EnumVisitor,
+    {
+        let value = match self.value.take() {
+            Some(Bson::Document(value)) => value,
+            Some(_) => { return Err(de::Error::syntax("expected an enum")); }
+            None => { return Err(de::Error::end_of_stream()); }
+        };
+
+        let mut iter = value.into_iter();
+
+        let (variant, value) = match iter.next() {
+            Some(v) => v,
+            None => return Err(de::Error::syntax("expected a variant name")),
+        };
+
+        // enums are encoded in json as maps with a single key:value pair
+        match iter.next() {
+            Some(_) => Err(de::Error::syntax("expected map")),
+            None => visitor.visit(VariantDecoder {
+                de: self,
+                val: Some(value),
+                variant: Some(Bson::String(variant)),
+            }),
+        }
+    }
+
+    #[inline]
+    fn visit_newtype_struct<V>(&mut self,
+                               _name: &'static str,
+                               mut visitor: V) -> DecoderResult<V::Value>
+        where V: Visitor,
+    {
+        visitor.visit_newtype_struct(self)
+    }
+
+    #[inline]
+    fn format() -> &'static str {
+        "json"
+    }
+}
+
+struct VariantDecoder<'a> {
+    de: &'a mut Decoder,
+    val: Option<Bson>,
+    variant: Option<Bson>,
+}
+
+impl<'a> VariantVisitor for VariantDecoder<'a> {
+    type Error = DecoderError;
+
+    fn visit_variant<V>(&mut self) -> DecoderResult<V>
+        where V: Deserialize,
+    {
+        Deserialize::deserialize(&mut Decoder::new(try!(self.variant.take()
+                                                        .ok_or(DecoderError::EndOfStream))))
+    }
+
+    fn visit_unit(&mut self) -> DecoderResult<()> {
+        Deserialize::deserialize(&mut Decoder::new(try!(self.val.take()
+                                                        .ok_or(DecoderError::EndOfStream))))
+    }
+
+    fn visit_newtype<T>(&mut self) -> DecoderResult<T>
+        where T: Deserialize,
+    {
+        Deserialize::deserialize(&mut Decoder::new(try!(self.val.take()
+                                                        .ok_or(DecoderError::EndOfStream))))
+    }
+
+    fn visit_tuple<V>(&mut self,
+                      _len: usize,
+                      visitor: V) -> DecoderResult<V::Value>
+        where V: Visitor,
+    {
+        if let Bson::Array(fields) = try!(self.val.take()
+                                          .ok_or(DecoderError::EndOfStream)) {
+            Deserializer::visit(
+                &mut SeqDecoder {
+                    de: self.de,
+                    len: fields.len(),
+                    iter: fields.into_iter(),
+                },
+                visitor,
+            )
+        } else {
+            Err(de::Error::syntax("expected a tuple"))
+        }
+    }
+
+    fn visit_struct<V>(&mut self,
+                       _fields: &'static[&'static str],
+                       visitor: V) -> DecoderResult<V::Value>
+        where V: Visitor,
+    {
+        if let Bson::Document(fields) = try!(self.val.take()
+                                             .ok_or(DecoderError::EndOfStream)) {
+            Deserializer::visit(
+                &mut MapDecoder {
+                    de: self.de,
+                    len: fields.len(),
+                    iter: fields.into_iter(),
+                    value: None,
+                },
+                visitor,
+            )
+        } else {
+            Err(de::Error::syntax("expected a struct"))
+        }
+    }
+}
+
+struct SeqDecoder<'a> {
+    de: &'a mut Decoder,
+    iter: vec::IntoIter<Bson>,
+    len: usize,
+}
+
+impl<'a> Deserializer for SeqDecoder<'a> {
+    type Error = DecoderError;
+
+    #[inline]
+    fn visit<V>(&mut self, mut visitor: V) -> DecoderResult<V::Value>
+        where V: Visitor,
+    {
+        if self.len == 0 {
+            visitor.visit_unit()
+        } else {
+            visitor.visit_seq(self)
+        }
+    }
+}
+
+impl<'a> SeqVisitor for SeqDecoder<'a> {
+    type Error = DecoderError;
+
+    fn visit<T>(&mut self) -> DecoderResult<Option<T>>
+        where T: Deserialize
+    {
+        match self.iter.next() {
+            Some(value) => {
+                self.len -= 1;
+                self.de.value = Some(value);
+                Ok(Some(try!(Deserialize::deserialize(self.de))))
+            }
+            None => Ok(None),
+        }
+    }
+
+    fn end(&mut self) -> DecoderResult<()> {
+        if self.len == 0 {
+            Ok(())
+        } else {
+            Err(de::Error::length_mismatch(self.len))
+        }
+    }
+
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        (self.len, Some(self.len))
+    }
+}
+
+struct MapDecoder<'a> {
+    de: &'a mut Decoder,
+    iter: OrderedDocumentIntoIterator,
+    value: Option<Bson>,
+    len: usize,
+}
+
+impl<'a> MapVisitor for MapDecoder<'a> {
+    type Error = DecoderError;
+
+    fn visit_key<T>(&mut self) -> DecoderResult<Option<T>>
+        where T: Deserialize
+    {
+        match self.iter.next() {
+            Some((key, value)) => {
+                self.len -= 1;
+                self.value = Some(value);
+                self.de.value = Some(Bson::String(key));
+                match Deserialize::deserialize(self.de) {
+                    Ok(val) => Ok(Some(val)),
+                    Err(DecoderError::UnknownField(_)) => Ok(None),
+                    Err(e) => Err(e),
+                }
+            }
+            None => Ok(None),
+        }
+    }
+
+    fn visit_value<T>(&mut self) -> DecoderResult<T>
+        where T: Deserialize
+    {
+        let value = try!(self.value.take()
+                         .ok_or(DecoderError::EndOfStream));
+
+        self.de.value = Some(value);
+        Ok(try!(Deserialize::deserialize(self.de)))
+    }
+
+    fn end(&mut self) -> DecoderResult<()> {
+        Ok(())
+    }
+
+    fn missing_field<V>(&mut self, _field: &'static str) -> DecoderResult<V>
+        where V: Deserialize,
+    {
+        // See if the type can deserialize from a unit.
+        struct UnitDecoder;
+
+        impl Deserializer for UnitDecoder {
+            type Error = DecoderError;
+
+            fn visit<V>(&mut self, mut visitor: V) -> DecoderResult<V::Value>
+                where V: Visitor,
+            {
+                visitor.visit_unit()
+            }
+
+            fn visit_option<V>(&mut self, mut visitor: V) -> DecoderResult<V::Value>
+                where V: Visitor,
+            {
+                visitor.visit_none()
+            }
+        }
+
+        Ok(try!(Deserialize::deserialize(&mut UnitDecoder)))
+    }
+
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        (self.len, Some(self.len))
+    }
+}
+
+impl<'a> Deserializer for MapDecoder<'a> {
+    type Error = DecoderError;
+
+    #[inline]
+    fn visit<V>(&mut self, mut visitor: V) -> DecoderResult<V::Value>
+        where V: Visitor,
+    {
+        visitor.visit_map(self)
+    }
+}
diff --git a/src/encoder/error.rs b/src/encoder/error.rs
new file mode 100644
index 00000000..9960a1b5
--- /dev/null
+++ b/src/encoder/error.rs
@@ -0,0 +1,55 @@
+use std::{io, error, fmt};
+use byteorder;
+use super::serde::State;
+
+/// Possible errors that can arise during encoding.
+#[derive(Debug)]
+pub enum EncoderError {
+    IoError(io::Error),
+    InvalidMapKeyType(State),
+    InvalidState(State),
+    EmptyState,
+}
+
+impl From<io::Error> for EncoderError {
+    fn from(err: io::Error) -> EncoderError {
+        EncoderError::IoError(err)
+    }
+}
+
+impl From<byteorder::Error> for EncoderError {
+    fn from(err: byteorder::Error) -> EncoderError {
+        EncoderError::IoError(From::from(err))
+    }
+}
+
+impl fmt::Display for EncoderError {
+    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+        match self {
+            &EncoderError::IoError(ref inner) => inner.fmt(fmt),
+            &EncoderError::InvalidMapKeyType(ref inner) => write!(fmt, "Invalid map key type: {:?}", inner),
+            &EncoderError::InvalidState(ref inner) => write!(fmt, "Invalid state emitted: {:?}", inner),
+            &EncoderError::EmptyState => write!(fmt, "No state emitted"),
+        }
+    }
+}
+
+impl error::Error for EncoderError {
+    fn description(&self) -> &str {
+        match self {
+            &EncoderError::IoError(ref inner) => inner.description(),
+            &EncoderError::InvalidMapKeyType(_) => "Invalid map key type",
+            &EncoderError::InvalidState(_) => "Invalid state emitted",
+            &EncoderError::EmptyState => "No state emitted",
+        }
+    }
+    fn cause(&self) -> Option<&error::Error> {
+        match self {
+            &EncoderError::IoError(ref inner) => Some(inner),
+            _ => None,
+        }
+    }
+}
+
+/// Alias for `Result<T, EncoderError>`.
+pub type EncoderResult<T> = Result<T, EncoderError>;
diff --git a/src/encoder.rs b/src/encoder/mod.rs
similarity index 81%
rename from src/encoder.rs
rename to src/encoder/mod.rs
index bd85173a..380c07c0 100644
--- a/src/encoder.rs
+++ b/src/encoder/mod.rs
@@ -21,56 +21,21 @@
 
 //! Encoder
 
-use std::io::{self, Write};
-use std::iter::IntoIterator;
-use std::{mem, error, fmt};
-use chrono::Timelike;
-
-use byteorder::{self, LittleEndian, WriteBytesExt};
-
-use bson::Bson;
-
-/// Possible errors that can arise during encoding.
-#[derive(Debug)]
-pub enum EncoderError {
-    IoError(io::Error),
-}
-
-impl From<io::Error> for EncoderError {
-    fn from(err: io::Error) -> EncoderError {
-        EncoderError::IoError(err)
-    }
-}
+mod error;
+mod serde;
 
-impl From<byteorder::Error> for EncoderError {
-    fn from(err: byteorder::Error) -> EncoderError {
-        EncoderError::IoError(From::from(err))
-    }
-}
+pub use self::error::{EncoderError, EncoderResult};
+pub use self::serde::Encoder;
 
-impl fmt::Display for EncoderError {
-    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
-        match self {
-            &EncoderError::IoError(ref inner) => inner.fmt(fmt)
-        }
-    }
-}
+use std::io::Write;
+use std::iter::IntoIterator;
+use std::mem;
 
-impl error::Error for EncoderError {
-    fn description(&self) -> &str {
-        match self {
-            &EncoderError::IoError(ref inner) => inner.description(),
-        }
-    }
-    fn cause(&self) -> Option<&error::Error> {
-        match self {
-            &EncoderError::IoError(ref inner) => Some(inner)
-        }
-    }
-}
+use chrono::Timelike;
+use byteorder::{LittleEndian, WriteBytesExt};
 
-/// Alias for `Result<T, EncoderError>`.
-pub type EncoderResult<T> = Result<T, EncoderError>;
+use bson::Bson;
+use serde::Serialize;
 
 fn write_string<W: Write + ?Sized>(writer: &mut W, s: &str) -> EncoderResult<()> {
     try!(writer.write_i32::<LittleEndian>(s.len() as i32 + 1));
@@ -169,3 +134,12 @@ fn encode_bson<W: Write + ?Sized>(writer: &mut W, key: &str, val: &Bson) -> Enco
         &Bson::Null => Ok(())
     }
 }
+
+/// Encode a `T` Serializable into a BSON `Value`.
+pub fn to_bson<T>(value: &T) -> EncoderResult<Bson>
+    where T: Serialize
+{
+    let mut ser = Encoder::new();
+    try!(value.serialize(&mut ser));
+    ser.bson()
+}
diff --git a/src/encoder/serde.rs b/src/encoder/serde.rs
new file mode 100644
index 00000000..6dbbb075
--- /dev/null
+++ b/src/encoder/serde.rs
@@ -0,0 +1,325 @@
+use serde::ser::{Serialize, Serializer, SeqVisitor, MapVisitor};
+use serde::ser::impls::MapIteratorVisitor;
+
+use bson::{self, Bson, Document};
+use oid::ObjectId;
+
+use super::{to_bson, EncoderError, EncoderResult};
+
+impl Serialize for ObjectId {
+    #[inline]
+    fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
+        where S: Serializer,
+    {
+        let mut doc = Document::new();
+        doc.insert("$oid".to_owned(), self.to_string());
+        serializer.visit_map(MapIteratorVisitor::new(doc.iter(), Some(doc.len())))
+    }
+}
+
+impl Serialize for Document {
+    #[inline]
+    fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
+        where S: Serializer,
+    {
+        serializer.visit_map(MapIteratorVisitor::new(self.iter(), Some(self.len())))
+    }
+}
+
+impl Serialize for Bson {
+    #[inline]
+    fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
+        where S: Serializer,
+    {
+        match *self {
+            Bson::FloatingPoint(v) => serializer.visit_f64(v),
+            Bson::String(ref v) => serializer.visit_str(v),
+            Bson::Array(ref v) => v.serialize(serializer),
+            Bson::Document(ref v) => v.serialize(serializer),
+            Bson::Boolean(v) => serializer.visit_bool(v),
+            Bson::Null => serializer.visit_unit(),
+            Bson::I32(v) => serializer.visit_i32(v),
+            Bson::I64(v) => serializer.visit_i64(v),                        
+            _ => {
+                let doc = self.to_extended_document();
+                doc.serialize(serializer)
+            }
+        }
+    }
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub enum State {
+    Bson(Bson),
+    Array(Vec<Bson>),
+    Document(bson::Document),
+}
+
+pub struct Encoder {
+    state: Vec<State>,
+}
+
+impl Encoder {
+    /// Construct a new `Serializer`.
+    pub fn new() -> Encoder {
+        Encoder {
+            state: Vec::with_capacity(4),
+        }
+    }
+
+    /// Unwrap the `Serializer` and return the `Value`.
+    pub fn bson(mut self) -> EncoderResult<Bson> {
+        match self.state.pop() {
+            Some(State::Bson(value)) => Ok(value),
+            Some(state) => Err(EncoderError::InvalidState(state)),
+            None => Err(EncoderError::EmptyState),
+        }
+    }
+
+    fn pop(&mut self) -> EncoderResult<State> {
+        match self.state.pop() {
+            Some(state) => Ok(state),
+            None => Err(EncoderError::EmptyState),
+        }
+    }
+}
+
+impl Serializer for Encoder {
+    type Error = EncoderError;
+
+    #[inline]
+    fn visit_bool(&mut self, value: bool) -> EncoderResult<()> {
+        self.state.push(State::Bson(Bson::Boolean(value)));
+        Ok(())
+    }
+
+    #[inline]
+    fn visit_i8(&mut self, value: i8) -> EncoderResult<()> {
+        self.visit_i32(value as i32)
+    }    
+
+    #[inline]
+    fn visit_i16(&mut self, value: i16) -> EncoderResult<()> {
+        self.visit_i32(value as i32)
+    }    
+
+    #[inline]
+    fn visit_i32(&mut self, value: i32) -> EncoderResult<()> {
+        self.state.push(State::Bson(Bson::I32(value)));
+        Ok(())
+    }
+
+    #[inline]
+    fn visit_i64(&mut self, value: i64) -> EncoderResult<()> {
+        self.state.push(State::Bson(Bson::I64(value)));
+        Ok(())
+    }
+
+    #[inline]
+    fn visit_u64(&mut self, value: u64) -> EncoderResult<()> {
+        self.state.push(State::Bson(Bson::FloatingPoint(value as f64)));
+        Ok(())
+    }
+
+    #[inline]
+    fn visit_f64(&mut self, value: f64) -> EncoderResult<()> {
+        self.state.push(State::Bson(Bson::FloatingPoint(value as f64)));
+        Ok(())
+    }
+
+    #[inline]
+    fn visit_char(&mut self, value: char) -> EncoderResult<()> {
+        let mut s = String::new();
+        s.push(value);
+        self.visit_str(&s)
+    }
+
+    #[inline]
+    fn visit_str(&mut self, value: &str) -> EncoderResult<()> {
+        self.state.push(State::Bson(Bson::String(String::from(value))));
+        Ok(())
+    }
+
+    #[inline]
+    fn visit_none(&mut self) -> EncoderResult<()> {
+        self.visit_unit()
+    }
+
+    #[inline]
+    fn visit_some<V>(&mut self, value: V) -> EncoderResult<()>
+        where V: Serialize,
+    {
+        value.serialize(self)
+    }
+
+    #[inline]
+    fn visit_unit(&mut self) -> EncoderResult<()> {
+        self.state.push(State::Bson(Bson::Null));
+        Ok(())
+    }
+
+    #[inline]
+    fn visit_unit_variant(&mut self,
+                          _name: &str,
+                          _variant_index: usize,
+                          variant: &str) -> EncoderResult<()> {
+
+        let mut values = bson::Document::new();
+        values.insert(String::from(variant), Bson::Array(vec![]));
+
+        self.state.push(State::Bson(Bson::Document(values)));
+        Ok(())
+    }
+
+    #[inline]
+    fn visit_newtype_variant<T>(&mut self,
+                                _name: &str,
+                                _variant_index: usize,
+                                variant: &str,
+                                value: T) -> EncoderResult<()>
+        where T: Serialize,
+    {
+        let mut values = bson::Document::new();
+        values.insert(String::from(variant), try!(to_bson(&value)));
+
+        self.state.push(State::Bson(Bson::Document(values)));
+        Ok(())
+    }
+
+    #[inline]
+    fn visit_seq<V>(&mut self, mut visitor: V) -> EncoderResult<()>
+        where V: SeqVisitor,
+    {
+        let len = visitor.len().unwrap_or(0);
+        let values = Vec::with_capacity(len);
+        self.state.push(State::Array(values));
+
+        while let Some(()) = try!(visitor.visit(self)) { }
+
+        let values = match try!(self.pop()) {
+            State::Array(values) => values,
+            state => return Err(EncoderError::InvalidState(state)),
+        };
+
+        self.state.push(State::Bson(Bson::Array(values)));
+        Ok(())
+    }
+
+    #[inline]
+    fn visit_tuple_variant<V>(&mut self,
+                              _name: &str,
+                              _variant_index: usize,
+                              variant: &str,
+                              visitor: V) -> EncoderResult<()>
+        where V: SeqVisitor,
+    {
+        try!(self.visit_seq(visitor));
+
+        let value = match try!(self.pop()) {
+            State::Bson(value) => value,
+            state => return Err(EncoderError::InvalidState(state)),
+        };
+
+        let mut object = bson::Document::new();
+        object.insert(String::from(variant), value);
+
+        self.state.push(State::Bson(Bson::Document(object)));
+        Ok(())
+    }
+
+    #[inline]
+    fn visit_seq_elt<T>(&mut self, value: T) -> EncoderResult<()>
+        where T: Serialize,
+    {
+        try!(value.serialize(self));
+
+        let value = match try!(self.pop()) {
+            State::Bson(value) => value,
+            state => return Err(EncoderError::InvalidState(state)),
+        };
+
+        match self.state.last_mut() {
+            Some(&mut State::Array(ref mut values)) => values.push(value),
+            Some(state) => return Err(EncoderError::InvalidState(state.clone())),
+            None => return Err(EncoderError::EmptyState),
+        }
+
+        Ok(())
+    }
+
+    #[inline]
+    fn visit_map<V>(&mut self, mut visitor: V) -> EncoderResult<()>
+        where V: MapVisitor,
+    {
+        let values = bson::Document::new();
+        self.state.push(State::Document(values));
+
+        while let Some(()) = try!(visitor.visit(self)) { }
+
+        let values = match try!(self.pop()) {
+            State::Document(values) => values,
+            state => return return Err(EncoderError::InvalidState(state)),
+        };
+
+        let bson = Bson::from_extended_document(values);
+        self.state.push(State::Bson(bson));
+        Ok(())
+    }
+
+    #[inline]
+    fn visit_struct_variant<V>(&mut self,
+                               _name: &str,
+                               _variant_index: usize,
+                               variant: &str,
+                               visitor: V) -> EncoderResult<()>
+        where V: MapVisitor,
+    {
+        try!(self.visit_map(visitor));
+
+        let value = match try!(self.pop()) {
+            State::Bson(value) => value,
+            state => return Err(EncoderError::InvalidState(state)),
+        };
+
+        let mut object = bson::Document::new();
+        object.insert(String::from(variant), value);
+
+        self.state.push(State::Bson(Bson::Document(object)));
+        Ok(())
+    }
+
+    #[inline]
+    fn visit_map_elt<K, V>(&mut self, key: K, value: V) -> EncoderResult<()>
+        where K: Serialize,
+              V: Serialize,
+    {
+        try!(key.serialize(self));
+
+        let key = match try!(self.pop()) {
+            State::Bson(Bson::String(value)) => value,
+            state => return Err(EncoderError::InvalidMapKeyType(state)),
+        };
+
+        try!(value.serialize(self));
+
+        let value = match try!(self.pop()) {
+            State::Bson(value) => value,
+            state => return Err(EncoderError::InvalidState(state)),
+        };
+
+        if Bson::Null != value {
+            match self.state.last_mut() {
+                Some(&mut State::Document(ref mut values)) => { values.insert(key, value); }
+                Some(state) => return Err(EncoderError::InvalidState(state.clone())),
+                None => return Err(EncoderError::EmptyState),
+            }
+        }
+
+        Ok(())
+    }
+
+    #[inline]
+    fn format() -> &'static str {
+        "bson"
+    }
+}
diff --git a/src/lib.rs b/src/lib.rs
index 57313dec..564cf2b4 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -48,13 +48,15 @@ extern crate crypto;
 extern crate libc;
 extern crate rand;
 extern crate rustc_serialize;
+extern crate serde;
 extern crate time;
 
 pub use self::bson::{Bson, Document, Array};
-pub use self::encoder::{encode_document, EncoderResult, EncoderError};
-pub use self::decoder::{decode_document, DecoderResult, DecoderError};
+pub use self::encoder::{encode_document, to_bson, Encoder, EncoderResult, EncoderError};
+pub use self::decoder::{decode_document, from_bson, Decoder, DecoderResult, DecoderError};
 pub use self::ordered::{ValueAccessError, ValueAccessResult};
 
+#[macro_use]
 pub mod macros;
 pub mod oid;
 pub mod spec;
diff --git a/src/macros.rs b/src/macros.rs
index 7041277e..46601637 100644
--- a/src/macros.rs
+++ b/src/macros.rs
@@ -1,5 +1,7 @@
 #[macro_export]
 macro_rules! bson {
+    ([]) => {{ $crate::Bson::Array(Vec::new()) }};
+
     ([$($val:tt),*]) => {{
         let mut array = Vec::new();
 
diff --git a/src/oid.rs b/src/oid.rs
index 5ee11741..5279348a 100644
--- a/src/oid.rs
+++ b/src/oid.rs
@@ -1,16 +1,17 @@
 use libc;
 
+use std::{fmt, io, error, result};
+use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
+
+use byteorder::{ByteOrder, BigEndian, LittleEndian};
 use crypto::digest::Digest;
 use crypto::md5::Md5;
 
-use byteorder::{ByteOrder, BigEndian, LittleEndian};
 use rand::{Rng, OsRng};
 use rustc_serialize::hex::{self, FromHex, ToHex};
 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
-use time;
 
-use std::{fmt, io, error, result};
-use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
+use time;
 
 const TIMESTAMP_SIZE: usize = 4;
 const MACHINE_ID_SIZE: usize = 3;
@@ -327,3 +328,4 @@ fn count_is_big_endian() {
     assert_eq!(0x22u8, oid.bytes()[COUNTER_OFFSET + 1]);
     assert_eq!(0x33u8, oid.bytes()[COUNTER_OFFSET + 2]);
 }
+
diff --git a/src/ordered.rs b/src/ordered.rs
index 8e88e9eb..185283bc 100644
--- a/src/ordered.rs
+++ b/src/ordered.rs
@@ -1,14 +1,13 @@
 use chrono::{DateTime, UTC};
-use bson::{Array,Bson,Document};
-use super::spec::BinarySubtype;
-use super::oid::ObjectId;
 use std::collections::BTreeMap;
-use std::error;
-use std::fmt;
+use std::{error, fmt, slice};
 use std::fmt::{Debug, Display, Error, Formatter};
 use std::iter::{FromIterator, Map};
 use std::vec::IntoIter;
-use std::slice;
+
+use bson::{Array,Bson,Document};
+use oid::ObjectId;
+use spec::BinarySubtype;
 
 /// Error to indicate that either a value was empty or it contained an unexpected
 /// type, for use with the direct getters.
@@ -365,3 +364,12 @@ impl OrderedDocument {
         self.document.remove(key)
     }
 }
+
+impl From<BTreeMap<String, Bson>> for OrderedDocument {
+    fn from(tree: BTreeMap<String, Bson>) -> OrderedDocument {        
+        OrderedDocument {
+            keys: tree.keys().cloned().collect(),
+            document: tree,
+        }
+    }
+}


Test patch:
diff --git a/serde-tests/Cargo.toml b/serde-tests/Cargo.toml
new file mode 100644
index 00000000..4d3aabe3
--- /dev/null
+++ b/serde-tests/Cargo.toml
@@ -0,0 +1,22 @@
+[package]
+name = "serde-tests"
+version = "0.1.0"
+authors = ["Kevin Yeh <kevinyeah@utexas.edu>"]
+build = "build.rs"
+
+
+[dependencies]
+serde = "0.6"
+bson = { path = "..", features = ["serde"] }
+
+[build-dependencies]
+syntex = "0.22"
+serde_codegen = "0.6"
+
+[lib]
+name = "serde_tests"
+path = "lib.rs"
+
+[[test]]
+name = "serde"
+path = "test.rs"
\ No newline at end of file
diff --git a/serde-tests/build.rs b/serde-tests/build.rs
new file mode 100644
index 00000000..7acbef5f
--- /dev/null
+++ b/serde-tests/build.rs
@@ -0,0 +1,17 @@
+extern crate syntex;
+extern crate serde_codegen;
+
+use std::env;
+use std::path::Path;
+
+fn main() {
+    let out_dir = env::var_os("OUT_DIR").unwrap();
+
+    let src = Path::new("test.rs.in");
+    let dst = Path::new(&out_dir).join("test.rs");
+
+    let mut registry = syntex::Registry::new();
+
+    serde_codegen::register(&mut registry);
+    registry.expand("", &src, &dst).unwrap();
+}
diff --git a/serde-tests/lib.rs b/serde-tests/lib.rs
new file mode 100644
index 00000000..65e2cc34
--- /dev/null
+++ b/serde-tests/lib.rs
@@ -0,0 +1,1 @@
+// intentionally blank
diff --git a/serde-tests/test.rs b/serde-tests/test.rs
new file mode 100644
index 00000000..e8de9fa9
--- /dev/null
+++ b/serde-tests/test.rs
@@ -0,0 +1,1 @@
+include!(concat!(env!("OUT_DIR"), "/test.rs"));
diff --git a/serde-tests/test.rs.in b/serde-tests/test.rs.in
new file mode 100644
index 00000000..00293219
--- /dev/null
+++ b/serde-tests/test.rs.in
@@ -0,0 +1,471 @@
+extern crate bson;
+extern crate serde;
+
+use std::collections::{BTreeMap, HashSet};
+use serde::{Deserialize, Serialize, Deserializer};
+
+use bson::{Bson, Encoder, Decoder, DecoderError};
+
+macro_rules! bson {
+    ([]) => {{ bson::Bson::Array(Vec::new()) }};
+
+    ([$($val:tt),*]) => {{
+        let mut array = Vec::new();
+
+        $(
+            array.push(bson!($val));
+        )*
+
+        bson::Bson::Array(array)
+    }};
+
+    ([$val:expr]) => {{
+        bson::Bson::Array(vec!(::std::convert::From::from($val)))
+    }};
+
+    ({ $($k:expr => $v:tt),* }) => {{
+        bdoc! {
+            $(
+                $k => $v
+            ),*
+        }
+    }};
+
+    ($val:expr) => {{
+        ::std::convert::From::from($val)
+    }};
+}
+
+macro_rules! bdoc {
+    () => {{ Bson::Document(bson::Document::new()) }};
+
+    ( $($key:expr => $val:tt),* ) => {{
+        let mut document = bson::Document::new();
+
+        $(
+            document.insert_bson($key.to_owned(), bson!($val));
+        )*
+
+        Bson::Document(document)
+    }};
+}
+
+macro_rules! t {
+    ($e:expr) => (match $e {
+        Ok(t) => t,
+        Err(e) => panic!("Failed with {:?}", e),
+    })
+}
+
+macro_rules! encode( ($t:expr) => ({
+    let mut e = Encoder::new();
+    t!($t.serialize(&mut e));
+    match e.bson() {
+        Ok(b) => b,
+        Err(e) => panic!("Failed to serialize: {}", e),
+    }
+}) );
+
+macro_rules! decode( ($t:expr) => ({
+    let mut d = Decoder::new($t);
+    t!(Deserialize::deserialize(&mut d))
+}) );
+
+#[test]
+fn smoke() {
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Foo { a: isize }
+    
+    let v = Foo { a: 2 };
+    assert_eq!(encode!(v), bdoc! {"a" => (2 as i64)});
+    assert_eq!(v, decode!(encode!(v)));
+}
+
+#[test]
+fn smoke_under() {
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Foo { a_b: isize }
+
+    let v = Foo { a_b: 2 };
+    assert_eq!(encode!(v), bdoc! { "a_b" => (2 as i64) });
+    assert_eq!(v, decode!(encode!(v)));
+
+    let mut m = BTreeMap::new();
+    m.insert("a_b".to_string(), 2 as i64);
+    assert_eq!(v, decode!(encode!(m)));
+}
+
+#[test]
+fn nested() {
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Foo { a: isize, b: Bar }
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Bar { a: String }
+
+    let v = Foo { a: 2, b: Bar { a: "test".to_string() } };
+    assert_eq!(encode!(v),
+               bdoc! {
+                   "a" => (2 as i64),
+                   "b" => {
+                       "a" => "test"
+                   }
+               });
+    assert_eq!(v, decode!(encode!(v)));
+}
+
+#[test]
+fn application_decode_error() {
+    #[derive(PartialEq, Debug)]
+    struct Range10(usize);
+    impl Deserialize for Range10 {
+         fn deserialize<D: Deserializer>(d: &mut D) -> Result<Range10, D::Error> {
+             let x: usize = try!(Deserialize::deserialize(d));
+             if x > 10 {
+                 Err(serde::de::Error::syntax("more than 10"))
+             } else {
+                 Ok(Range10(x))
+             }
+         }
+    }
+    let mut d_good = Decoder::new(Bson::I64(5));
+    let mut d_bad1 = Decoder::new(Bson::String("not an isize".to_string()));
+    let mut d_bad2 = Decoder::new(Bson::I64(11));
+
+    assert_eq!(Range10(5), t!(Deserialize::deserialize(&mut d_good)));
+
+    let err1: Result<Range10, _> = Deserialize::deserialize(&mut d_bad1);
+    assert!(err1.is_err());
+    let err2: Result<Range10, _> = Deserialize::deserialize(&mut d_bad2);
+    assert!(err2.is_err());
+}
+
+#[test]
+fn array() {
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Foo { a: Vec<i32> }
+
+    let v = Foo { a: vec![1, 2, 3, 4] };
+    assert_eq!(encode!(v),
+               bdoc! {
+                   "a" => [1, 2, 3, 4]
+               });
+    assert_eq!(v, decode!(encode!(v)));
+}
+
+#[test]
+fn tuple() {
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Foo { a: (i32, i32, i32, i32) }
+
+    let v = Foo { a: (1, 2, 3, 4) };
+    assert_eq!(encode!(v),
+               bdoc! {
+                   "a" => [1, 2, 3, 4]
+               });
+    assert_eq!(v, decode!(encode!(v)));
+}
+
+#[test]
+fn inner_structs_with_options() {
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Foo {
+        a: Option<Box<Foo>>,
+        b: Bar,
+    }
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Bar {
+        a: String,
+        b: f64,
+    }
+
+    let v = Foo {
+        a: Some(Box::new(Foo {
+            a: None,
+            b: Bar { a: "foo".to_string(), b: 4.5 },
+        })),
+        b: Bar { a: "bar".to_string(), b: 1.0 },
+    };
+    assert_eq!(encode!(v),
+               bdoc! {
+                   "a" => {
+                       "b" => {
+                           "a" => "foo",
+                           "b" => (4.5)
+                       }
+                   },
+                   "b" => {
+                       "a" => "bar",
+                       "b" => (1.0)
+                   }
+               });
+    assert_eq!(v, decode!(encode!(v)));
+}
+
+#[test]
+fn hashmap() {
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Foo {
+        map: BTreeMap<String, i32>,
+        set: HashSet<char>,
+    }
+
+    let v = Foo {
+        map: {
+            let mut m = BTreeMap::new();
+            m.insert("bar".to_string(), 4);
+            m.insert("foo".to_string(), 10);
+            m
+        },
+        set: {
+            let mut s = HashSet::new();
+            s.insert('a');
+            s
+        },
+    };
+    assert_eq!(encode!(v),
+        bdoc! {
+            "map" => {
+                "bar" => 4,
+                "foo" => 10
+            },
+            "set" => ["a"]
+        }
+    );
+    assert_eq!(v, decode!(encode!(v)));
+}
+
+#[test]
+fn tuple_struct() {
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Foo(i32, String, f64);
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Bar {
+        whee: Foo,
+    }
+
+    let v = Bar {
+        whee: Foo(1, "foo".to_string(), 4.5)
+    };
+    assert_eq!(
+        encode!(v),
+        bdoc! {
+            "whee" => [1, "foo", (4.5)]
+        }
+    );
+    assert_eq!(v, decode!(encode!(v)));
+}
+
+#[test]
+fn table_array() {
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Foo { a: Vec<Bar>, }
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Bar { a: i32 }
+
+    let v = Foo { a: vec![Bar { a: 1 }, Bar { a: 2 }] };
+    assert_eq!(
+        encode!(v),
+        bdoc! {
+            "a" => [{"a" => 1}, {"a" => 2}]
+        }
+    );
+    assert_eq!(v, decode!(encode!(v)));
+}
+
+
+#[test]
+fn type_conversion() {
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Foo { bar: i32 }
+
+    let mut d = Decoder::new(bdoc!{
+        "bar" => (1.0)
+    });
+    let a: Result<Foo, DecoderError> = Deserialize::deserialize(&mut d);
+    assert_eq!(
+        a.unwrap(),
+        Foo { bar: 1 }
+    );
+}
+
+#[test]
+fn missing_errors() {
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Foo { bar: i32 }
+
+    let mut d = Decoder::new(bdoc! {});
+    let a: Result<Foo, DecoderError> = Deserialize::deserialize(&mut d);
+    
+    assert!(a.is_err());
+}
+
+#[test]
+fn parse_enum() {
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Foo { a: E }
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    enum E {
+        Bar(i32),
+        Baz(f64),
+        Last(Foo2),
+    }
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Foo2 {
+        test: String,
+    }
+
+    let v = Foo { a: E::Bar(10) };
+    // technically serde is correct here. a single element tuple still is a
+    // tuple and therefor a sequence
+    assert_eq!(
+        encode!(v),
+        bdoc! { "a" => { "Bar" => 10 } }
+    );
+    assert_eq!(v, decode!(encode!(v)));
+
+    let v = Foo { a: E::Baz(10.2) };
+    assert_eq!(
+        encode!(v),
+        bdoc! { "a" => { "Baz" => (10.2) } }
+    );
+    assert_eq!(v, decode!(encode!(v)));
+
+    let v = Foo { a: E::Last(Foo2 { test: "test".to_string() }) };
+    assert_eq!(
+        encode!(v),
+        bdoc! { "a" => { "Last" => { "test" => "test" } } }
+    );
+    assert_eq!(v, decode!(encode!(v)));
+}
+
+#[test]
+fn unused_fields() {
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Foo { a: i32 }
+
+    let v = Foo { a: 2 };
+    let mut d = Decoder::new(bdoc! {
+        "a" => 2,
+        "b" => 5
+    });
+
+    assert_eq!(v, t!(Deserialize::deserialize(&mut d)));
+}
+
+#[test]
+fn unused_fields2() {
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Foo { a: Bar }
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Bar { a: i32 }
+
+    let v = Foo { a: Bar { a: 2 } };
+    let mut d = Decoder::new(bdoc! {
+        "a" => {
+            "a" => 2,
+            "b" => 5
+        }
+    });
+    
+    assert_eq!(v, t!(Deserialize::deserialize(&mut d)));
+}
+
+#[test]
+fn unused_fields3() {
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Foo { a: Bar }
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Bar { a: i32 }
+    
+    let v = Foo { a: Bar { a: 2 } };
+    let mut d = Decoder::new(bdoc! {
+        "a" => {
+            "a" => 2
+        }
+    });
+    assert_eq!(v, t!(Deserialize::deserialize(&mut d)));
+}
+
+#[test]
+fn unused_fields4() {
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Foo { a: BTreeMap<String, String> }
+    
+    let mut map = BTreeMap::new();
+    map.insert("a".to_owned(), "foo".to_owned());
+    let v = Foo { a: map };
+    let mut d = Decoder::new(bdoc! {
+        "a" => {
+            "a" => "foo"
+        }
+    });
+    assert_eq!(v, t!(Deserialize::deserialize(&mut d)));
+}
+
+#[test]
+fn unused_fields5() {
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Foo { a: Vec<String> }
+
+    let v = Foo { a: vec!["a".to_string()] };
+    let mut d = Decoder::new(bdoc! {
+        "a" => ["a"]
+    });
+    assert_eq!(v, t!(Deserialize::deserialize(&mut d)));
+}
+
+#[test]
+fn unused_fields6() {
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Foo { a: Option<Vec<String>> }
+
+    let v = Foo { a: Some(vec![]) };
+    let mut d = Decoder::new(bdoc! {
+        "a" => []
+    });
+    assert_eq!(v, t!(Deserialize::deserialize(&mut d)));
+}
+
+#[test]
+fn unused_fields7() {
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Foo { a: Vec<Bar> }
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Bar { a: i32 }
+
+    let v = Foo { a: vec![Bar { a: 1 }] };
+    let mut d = Decoder::new(bdoc! {
+        "a" => [{"a" => 1, "b" => 2}]
+    });
+    assert_eq!(v, t!(Deserialize::deserialize(&mut d)));
+}
+
+#[test]
+fn empty_arrays() {
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Foo { a: Vec<Bar> }
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Bar;
+
+    let v = Foo { a: vec![] };
+    let mut d = Decoder::new(bdoc! {});
+    assert_eq!(v, t!(Deserialize::deserialize(&mut d)));
+}
+
+#[test]
+fn empty_arrays2() {
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Foo { a: Option<Vec<Bar>> }
+    #[derive(Serialize, Deserialize, PartialEq, Debug)]
+    struct Bar;
+    
+    let v = Foo { a: None };
+    let mut d = Decoder::new(bdoc! {});
+    assert_eq!(v, t!(Deserialize::deserialize(&mut d)));
+
+    let v = Foo { a: Some(vec![]) };
+    let mut d = Decoder::new(bdoc! {
+        "a" => []
+    });
+    assert_eq!(v, t!(Deserialize::deserialize(&mut d)));
+}
diff --git a/tests/modules/mod.rs b/tests/modules/mod.rs
index 28d6b6ce..4c22f96d 100644
--- a/tests/modules/mod.rs
+++ b/tests/modules/mod.rs
@@ -3,3 +3,4 @@ mod macros;
 mod oid;
 mod ordered;
 mod bson;
+mod ser;
diff --git a/tests/modules/ser.rs b/tests/modules/ser.rs
new file mode 100644
index 00000000..6553285e
--- /dev/null
+++ b/tests/modules/ser.rs
@@ -0,0 +1,79 @@
+use bson::{Bson, to_bson, from_bson};
+use bson::oid::ObjectId;
+use std::collections::BTreeMap;
+
+#[test]
+fn floating_point() {
+    let obj = Bson::FloatingPoint(240.5);
+    let f: f64 = from_bson(obj.clone()).unwrap();
+    assert_eq!(f, 240.5);
+
+    let deser: Bson = to_bson(&f).unwrap();
+    assert_eq!(obj, deser);
+}
+
+#[test]
+fn string() {
+    let obj = Bson::String("avocado".to_owned());
+    let s: String = from_bson(obj.clone()).unwrap();
+    assert_eq!(s, "avocado");
+
+    let deser: Bson = to_bson(&s).unwrap();
+    assert_eq!(obj, deser);
+}
+
+#[test]
+fn arr() {
+    let obj = Bson::Array(vec![Bson::I32(0), Bson::I32(1), Bson::I32(2), Bson::I32(3)]);
+    let arr: Vec<i32> = from_bson(obj.clone().clone()).unwrap();
+    assert_eq!(arr, vec![0i32, 1i32, 2i32, 3i32]);
+
+    let deser: Bson = to_bson(&arr).unwrap();
+    assert_eq!(deser, obj);
+}
+
+#[test]
+fn boolean() {
+    let obj = Bson::Boolean(true);
+    let b: bool = from_bson(obj.clone()).unwrap();
+    assert_eq!(b, true);
+
+    let deser: Bson = to_bson(&b).unwrap();
+    assert_eq!(deser, obj);
+}
+
+#[test]
+fn int32() {
+    let obj = Bson::I32(101);
+    let i: i32 = from_bson(obj.clone()).unwrap();
+
+    assert_eq!(i, 101);
+
+    let deser: Bson = to_bson(&i).unwrap();
+    assert_eq!(deser, obj);
+}
+
+#[test]
+fn int64() {
+    let obj = Bson::I64(101);
+    let i: i64 = from_bson(obj.clone()).unwrap();
+
+    assert_eq!(i, 101);
+
+    let deser: Bson = to_bson(&i).unwrap();
+    assert_eq!(deser, obj);
+}
+
+#[test]
+fn oid() {
+    let oid = ObjectId::new().unwrap();
+    let obj = Bson::ObjectId(oid.clone());
+    let s: BTreeMap<String, String> = from_bson(obj.clone()).unwrap();
+
+    let mut expected = BTreeMap::new();
+    expected.insert("$oid".to_owned(), oid.to_string());
+    assert_eq!(s, expected);
+
+    let deser: Bson = to_bson(&s).unwrap();
+    assert_eq!(deser, obj);
+}