Skip to content

Commit f515d99

Browse files
committed
Refactor serialization
1 parent 4f2f585 commit f515d99

File tree

5 files changed

+133
-123
lines changed

5 files changed

+133
-123
lines changed

src/bson.rs

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -345,12 +345,14 @@ impl Bson {
345345
}
346346

347347
pub fn from_extended_document(values: Document) -> Result<Bson, Error> {
348-
if let Some(&Bson::String(ref pat)) = values.get("$regex") {
349-
if let Some(&Bson::String(ref opt)) = values.get("$options") {
350-
return Ok(Bson::RegExp(pat.to_owned(), opt.to_owned()));
348+
if values.contains_key("$regex") {
349+
if let Some(&Bson::String(ref pat)) = values.get("$regex") {
350+
if let Some(&Bson::String(ref opt)) = values.get("$options") {
351+
return Ok(Bson::RegExp(pat.to_owned(), opt.to_owned()));
352+
}
351353
}
352354
} else if let Some(&Bson::String(ref code)) = values.get("$code") {
353-
if let Some(&Bson::Document(ref scope)) = values.get("$sscope") {
355+
if let Some(&Bson::Document(ref scope)) = values.get("$scope") {
354356
return Ok(Bson::JavaScriptCodeWithScope(code.to_owned(), scope.to_owned()));
355357
} else {
356358
return Ok(Bson::JavaScriptCode(code.to_owned()));
@@ -363,12 +365,13 @@ impl Bson {
363365
return Ok(Bson::Binary(From::from(ttype), hex.from_hex().unwrap()));
364366
}
365367
} else if let Some(&Bson::String(ref hex)) = values.get("$oid") {
368+
println!("RETURNING OID");
366369
return Ok(Bson::ObjectId(oid::ObjectId::with_string(hex).unwrap()));
367370
} else if let Some(&Bson::Document(ref doc)) = values.get("$date") {
368371
if let Some(&Bson::I64(long)) = doc.get("$numberLong") {
369372
return Ok(Bson::UtcDatetime(UTC.timestamp(long / 1000, (long % 1000) as u32 * 1000000)));
370373
}
371-
}
374+
}
372375

373376
Ok(Bson::Document(values))
374377
}

src/oid.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,11 @@ use time;
1111

1212
use std::{fmt, io, error, result};
1313
use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
14+
use serde::ser::{Serialize, Serializer};
15+
use serde::de::{Deserialize, Deserializer};
16+
use serde::ser::impls::MapIteratorVisitor;
17+
use bson::{Bson, Document};
18+
use ser::BsonVisitor;
1419

1520
const TIMESTAMP_SIZE: usize = 4;
1621
const MACHINE_ID_SIZE: usize = 3;
@@ -327,3 +332,28 @@ fn count_is_big_endian() {
327332
assert_eq!(0x22u8, oid.bytes()[COUNTER_OFFSET + 1]);
328333
assert_eq!(0x33u8, oid.bytes()[COUNTER_OFFSET + 2]);
329334
}
335+
336+
impl Serialize for ObjectId {
337+
#[inline]
338+
fn serialize<S>(&self, serializer: &mut S) -> result::Result<(), S::Error>
339+
where S: Serializer,
340+
{
341+
let mut doc = Document::new();
342+
doc.insert("$oid".to_owned(), self.to_string());
343+
serializer.visit_map(MapIteratorVisitor::new(doc.iter(), Some(doc.len())))
344+
}
345+
}
346+
347+
impl Deserialize for ObjectId {
348+
/// Deserialize this value given this `Deserializer`.
349+
fn deserialize<D>(deserializer: &mut D) -> result::Result<Self, D::Error>
350+
where D: Deserializer,
351+
{
352+
deserializer.visit_map(BsonVisitor)
353+
.and_then(|bson| if let Bson::ObjectId(oid) = bson {
354+
Ok(oid)
355+
} else {
356+
unimplemented!()
357+
})
358+
}
359+
}

src/ser.rs

Lines changed: 81 additions & 118 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,80 @@ impl de::Error for Error {
187187
}
188188
}
189189

190+
pub struct BsonVisitor;
191+
192+
impl de::Visitor for BsonVisitor {
193+
type Value = Bson;
194+
195+
#[inline]
196+
fn visit_bool<E>(&mut self, value: bool) -> Result<Bson, E> {
197+
Ok(Bson::Boolean(value))
198+
}
199+
200+
#[inline]
201+
fn visit_i64<E>(&mut self, value: i64) -> Result<Bson, E> {
202+
Ok(Bson::I64(value))
203+
}
204+
205+
#[inline]
206+
fn visit_u64<E>(&mut self, value: u64) -> Result<Bson, E> {
207+
Ok(Bson::FloatingPoint(value as f64))
208+
}
209+
210+
#[inline]
211+
fn visit_f64<E>(&mut self, value: f64) -> Result<Bson, E> {
212+
Ok(Bson::FloatingPoint(value))
213+
}
214+
215+
#[inline]
216+
fn visit_str<E>(&mut self, value: &str) -> Result<Bson, E>
217+
where E: de::Error,
218+
{
219+
self.visit_string(String::from(value))
220+
}
221+
222+
#[inline]
223+
fn visit_string<E>(&mut self, value: String) -> Result<Bson, E> {
224+
Ok(Bson::String(value))
225+
}
226+
227+
#[inline]
228+
fn visit_none<E>(&mut self) -> Result<Bson, E> {
229+
Ok(Bson::Null)
230+
}
231+
232+
#[inline]
233+
fn visit_some<D>(&mut self, deserializer: &mut D) -> Result<Bson, D::Error>
234+
where D: de::Deserializer,
235+
{
236+
de::Deserialize::deserialize(deserializer)
237+
}
238+
239+
#[inline]
240+
fn visit_unit<E>(&mut self) -> Result<Bson, E> {
241+
Ok(Bson::Null)
242+
}
243+
244+
#[inline]
245+
fn visit_seq<V>(&mut self, visitor: V) -> Result<Bson, V::Error>
246+
where V: de::SeqVisitor,
247+
{
248+
let values = try!(de::impls::VecVisitor::new().visit_seq(visitor));
249+
Ok(Bson::Array(values))
250+
}
251+
252+
#[inline]
253+
fn visit_map<V>(&mut self, visitor: V) -> Result<Bson, V::Error>
254+
where V: de::MapVisitor,
255+
{
256+
let values = try!(de::impls::BTreeMapVisitor::new().visit_map(visitor));
257+
let values2 = values.clone();
258+
println!("{:?}", Bson::from_extended_document(values2.into()));
259+
Ok(Bson::from_extended_document(values.into()).unwrap())
260+
}
261+
}
262+
263+
190264
#[derive(Debug)]
191265
enum State {
192266
Bson(Bson),
@@ -382,7 +456,9 @@ impl ser::Serializer for Serializer {
382456
state => panic!("expected object, found {:?}", state),
383457
};
384458

459+
println!("VALUES FROM VISIT_MAP: {:?} // {:?}", &values, values.get("$oid"));
385460
let bson = Bson::from_extended_document(values).unwrap();
461+
386462
self.state.push(State::Bson(bson));
387463
Ok(())
388464
}
@@ -423,13 +499,17 @@ impl ser::Serializer for Serializer {
423499
state => panic!("expected key, found {:?}", state),
424500
};
425501

502+
println!("SERIALIZED KEY: {:?}", &key);
503+
426504
try!(value.serialize(self));
427505

428506
let value = match self.state.pop().unwrap() {
429507
State::Bson(value) => value,
430508
state => panic!("expected value, found {:?}", state),
431509
};
432510

511+
println!("SERIALIZED VALUE: {:?}", &value);
512+
433513
match *self.state.last_mut().unwrap() {
434514
State::Document(ref mut values) => { values.insert(key, value); }
435515
ref state => panic!("expected object, found {:?}", state),
@@ -497,6 +577,7 @@ impl de::Deserializer for Deserializer {
497577
_ => {
498578
let doc = value.to_extended_document();
499579
let len = doc.len();
580+
println!("{:?}", doc);
500581
visitor.visit_map(MapDeserializer {
501582
de: self,
502583
iter: doc.into_iter(),
@@ -787,77 +868,6 @@ impl de::Deserialize for Bson {
787868
fn deserialize<D>(deserializer: &mut D) -> Result<Bson, D::Error>
788869
where D: de::Deserializer,
789870
{
790-
struct BsonVisitor;
791-
792-
impl de::Visitor for BsonVisitor {
793-
type Value = Bson;
794-
795-
#[inline]
796-
fn visit_bool<E>(&mut self, value: bool) -> Result<Bson, E> {
797-
Ok(Bson::Boolean(value))
798-
}
799-
800-
#[inline]
801-
fn visit_i64<E>(&mut self, value: i64) -> Result<Bson, E> {
802-
Ok(Bson::I64(value))
803-
}
804-
805-
#[inline]
806-
fn visit_u64<E>(&mut self, value: u64) -> Result<Bson, E> {
807-
Ok(Bson::FloatingPoint(value as f64))
808-
}
809-
810-
#[inline]
811-
fn visit_f64<E>(&mut self, value: f64) -> Result<Bson, E> {
812-
Ok(Bson::FloatingPoint(value))
813-
}
814-
815-
#[inline]
816-
fn visit_str<E>(&mut self, value: &str) -> Result<Bson, E>
817-
where E: de::Error,
818-
{
819-
self.visit_string(String::from(value))
820-
}
821-
822-
#[inline]
823-
fn visit_string<E>(&mut self, value: String) -> Result<Bson, E> {
824-
Ok(Bson::String(value))
825-
}
826-
827-
#[inline]
828-
fn visit_none<E>(&mut self) -> Result<Bson, E> {
829-
Ok(Bson::Null)
830-
}
831-
832-
#[inline]
833-
fn visit_some<D>(&mut self, deserializer: &mut D) -> Result<Bson, D::Error>
834-
where D: de::Deserializer,
835-
{
836-
de::Deserialize::deserialize(deserializer)
837-
}
838-
839-
#[inline]
840-
fn visit_unit<E>(&mut self) -> Result<Bson, E> {
841-
Ok(Bson::Null)
842-
}
843-
844-
#[inline]
845-
fn visit_seq<V>(&mut self, visitor: V) -> Result<Bson, V::Error>
846-
where V: de::SeqVisitor,
847-
{
848-
let values = try!(de::impls::VecVisitor::new().visit_seq(visitor));
849-
Ok(Bson::Array(values))
850-
}
851-
852-
#[inline]
853-
fn visit_map<V>(&mut self, visitor: V) -> Result<Bson, V::Error>
854-
where V: de::MapVisitor,
855-
{
856-
let values = try!(de::impls::BTreeMapVisitor::new().visit_map(visitor));
857-
Ok(Bson::from_extended_document(values.into()).unwrap())
858-
}
859-
}
860-
861871
deserializer.visit(BsonVisitor)
862872
}
863873
}
@@ -878,50 +888,3 @@ pub fn from_bson<T>(bson: Bson) -> Result<T, Error>
878888
let mut de = Deserializer::new(bson);
879889
de::Deserialize::deserialize(&mut de)
880890
}
881-
882-
883-
///////////////
884-
/*
885-
pub struct OrderedMapIteratorVisitor<Iter> {
886-
iter: Iter,
887-
len: Option<usize>,
888-
}
889-
890-
impl<K, V, Iter> OrderedMapIteratorVisitor<Iter>
891-
where Iter: Iterator<Item=(K, V)>
892-
{
893-
/// Construct a new `MapIteratorVisitor<Iter>`.
894-
#[inline]
895-
pub fn new(iter: Iter, len: Option<usize>) -> MapIteratorVisitor<Iter> {
896-
MapIteratorVisitor {
897-
iter: iter,
898-
len: len,
899-
}
900-
}
901-
}
902-
903-
impl<K, V, I> MapVisitor for MapIteratorVisitor<I>
904-
where K: Serialize,
905-
V: Serialize,
906-
I: Iterator<Item=(K, V)>,
907-
{
908-
#[inline]
909-
fn visit<S>(&mut self, serializer: &mut S) -> Result<Option<()>, S::Error>
910-
where S: Serializer,
911-
{
912-
match self.iter.next() {
913-
Some((key, value)) => {
914-
let value = try!(serializer.serialize_map_elt(key, value));
915-
Ok(Some(value))
916-
}
917-
None => Ok(None)
918-
}
919-
}
920-
921-
#[inline]
922-
fn len(&self) -> Option<usize> {
923-
self.len
924-
}
925-
}
926-
*/
927-
///////////////////////////////////////////////////////////////////////////////

tests/modules/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,4 @@ mod macros;
33
mod oid;
44
mod ordered;
55
mod bson;
6+
mod ser;

tests/modules/ser.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
use bson::{Bson, Document, to_bson, from_bson};
2+
use bson::oid::ObjectId;
3+
use std::collections::BTreeMap;
4+
5+
#[test]
6+
fn map() {
7+
let obj = Bson::ObjectId(ObjectId::new().unwrap());
8+
let s: BTreeMap<String, String> = from_bson(obj).unwrap();
9+
println!("{:?}", s);
10+
let deser: Bson = to_bson(&s);
11+
println!("{:?}", deser);
12+
assert_eq!(1, 2);
13+
}

0 commit comments

Comments
 (0)