Skip to content

Commit 936935a

Browse files
committed
[#89] Bug fixed, implements binary data visitors for serde
1 parent 6f6417c commit 936935a

File tree

3 files changed

+40
-14
lines changed

3 files changed

+40
-14
lines changed

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,4 @@ hex = "^0.2"
2929

3030
[dev-dependencies]
3131
serde_derive = "1.0"
32+
serde_bytes = "0.10"

src/decoder/serde.rs

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,16 @@
11
use std::fmt;
22
use std::vec;
33

4-
use serde::de::{self, Deserialize, DeserializeSeed, Deserializer, EnumAccess, MapAccess, SeqAccess, VariantAccess,
5-
Visitor};
4+
use serde::de::{
5+
self, Deserialize, DeserializeSeed, Deserializer, EnumAccess, MapAccess, SeqAccess, VariantAccess, Visitor,
6+
};
67
use serde::de::{Error, Unexpected};
78

89
use super::error::{DecoderError, DecoderResult};
910
use bson::{Bson, TimeStamp, UtcDateTime};
1011
use oid::ObjectId;
1112
use ordered::{OrderedDocument, OrderedDocumentIntoIterator, OrderedDocumentVisitor};
13+
use spec::BinarySubtype;
1214

1315
pub struct BsonVisitor;
1416

@@ -176,6 +178,13 @@ impl<'de> Visitor<'de> for BsonVisitor {
176178
let values = OrderedDocumentVisitor::new().visit_map(visitor)?;
177179
Ok(Bson::from_extended_document(values.into()))
178180
}
181+
182+
#[inline]
183+
fn visit_bytes<E>(self, v: &[u8]) -> Result<Bson, E>
184+
where E: Error
185+
{
186+
Ok(Bson::Binary(BinarySubtype::Generic, v.to_vec()))
187+
}
179188
}
180189

181190
/// Serde Decoder
@@ -256,6 +265,7 @@ impl<'de> Deserializer<'de> for Decoder {
256265
Bson::Null => visitor.visit_unit(),
257266
Bson::I32(v) => visitor.visit_i32(v),
258267
Bson::I64(v) => visitor.visit_i64(v),
268+
Bson::Binary(_, v) => visitor.visit_bytes(&v),
259269
_ => {
260270
let doc = value.to_extended_document();
261271
let len = doc.len();
@@ -309,10 +319,8 @@ impl<'de> Deserializer<'de> for Decoder {
309319
// enums are encoded in json as maps with a single key:value pair
310320
match iter.next() {
311321
Some(_) => Err(DecoderError::InvalidType("expected a single key:value pair".to_owned())),
312-
None => {
313-
visitor.visit_enum(EnumDecoder { val: Bson::String(variant),
314-
decoder: VariantDecoder { val: Some(value) }, })
315-
}
322+
None => visitor.visit_enum(EnumDecoder { val: Bson::String(variant),
323+
decoder: VariantDecoder { val: Some(value) }, }),
316324
}
317325
}
318326

tests/serde.rs

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ extern crate chrono;
44
extern crate serde;
55
#[macro_use]
66
extern crate serde_derive;
7+
extern crate serde_bytes;
78

89
use bson::{Bson, Decoder, Encoder};
910
use serde::{Deserialize, Serialize};
@@ -88,11 +89,10 @@ fn test_ser_datetime() {
8889
// FIXME: Due to BSON's datetime precision
8990
let now = now.with_nanosecond(now.nanosecond() / 1000000 * 1000000).unwrap();
9091

91-
let foo = Foo { date: From::from(now), };
92+
let foo = Foo { date: From::from(now) };
9293

9394
let x = bson::to_bson(&foo).unwrap();
94-
assert_eq!(x.as_document().unwrap(),
95-
&doc! { "date": (Bson::UtcDatetime(now)) });
95+
assert_eq!(x.as_document().unwrap(), &doc! { "date": (Bson::UtcDatetime(now)) });
9696

9797
let xfoo: Foo = bson::from_bson(x).unwrap();
9898
assert_eq!(xfoo, foo);
@@ -116,21 +116,38 @@ fn test_compat_u2f() {
116116

117117
#[test]
118118
fn test_byte_vec() {
119-
use std::io::Cursor;
120-
121-
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
119+
#[derive(Serialize, Debug, Eq, PartialEq)]
122120
pub struct AuthChallenge<'a> {
121+
#[serde(with = "serde_bytes")]
123122
pub challenge: &'a [u8],
124123
}
125124

126-
let x = AuthChallenge { challenge: b"18762b98b7c34c25bf9dc3154e4a5ca3" };
125+
let x = AuthChallenge { challenge: b"18762b98b7c34c25bf9dc3154e4a5ca3", };
127126

128127
let b = bson::to_bson(&x).unwrap();
129-
// assert_eq!(b, Bson::Document(doc! { "challenge": (Bson::Binary(bson::spec::BinarySubtype::Generic, x.challenge.clone()))}));
128+
assert_eq!(b, Bson::Document(doc! { "challenge": (Bson::Binary(bson::spec::BinarySubtype::Generic, x.challenge.to_vec()))}));
130129

131130
// let mut buf = Vec::new();
132131
// bson::encode_document(&mut buf, b.as_document().unwrap()).unwrap();
133132

134133
// let xb = bson::decode_document(&mut Cursor::new(buf)).unwrap();
135134
// assert_eq!(b.as_document().unwrap(), &xb);
136135
}
136+
137+
#[test]
138+
fn test_serde_bytes() {
139+
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
140+
pub struct Foo {
141+
#[serde(with = "serde_bytes")]
142+
data: Vec<u8>,
143+
}
144+
145+
let x = Foo { data: b"12345abcde".to_vec(), };
146+
147+
let b = bson::to_bson(&x).unwrap();
148+
assert_eq!(b.as_document().unwrap(),
149+
&doc! {"data": Bson::Binary(bson::spec::BinarySubtype::Generic, b"12345abcde".to_vec())});
150+
151+
let f = bson::from_bson::<Foo>(b).unwrap();
152+
assert_eq!(x, f);
153+
}

0 commit comments

Comments
 (0)