Skip to content

RUST-503 Support serializing directly to Document #210

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Aug 7, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/de/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -355,3 +355,11 @@ where
let de = Deserializer::new(bson);
Deserialize::deserialize(de)
}

/// Decode a BSON `Document` into a `T` Deserializable.
pub fn from_document<T>(doc: Document) -> Result<T>
where
T: DeserializeOwned,
{
from_bson(Bson::Document(doc))
}
4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,9 +196,9 @@ pub use self::{
Regex,
Timestamp,
},
de::{from_bson, Deserializer},
de::{from_bson, from_document, Deserializer},
decimal128::Decimal128,
ser::{to_bson, Serializer},
ser::{to_bson, to_document, Serializer},
};

#[macro_use]
Expand Down
18 changes: 17 additions & 1 deletion src/ser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ use chrono::Timelike;
#[cfg(feature = "decimal128")]
use crate::decimal128::Decimal128;
use crate::{
bson::{Binary, Bson, DbPointer, JavaScriptCodeWithScope, Regex},
bson::{Binary, Bson, DbPointer, Document, JavaScriptCodeWithScope, Regex},
spec::BinarySubtype,
};
use ::serde::Serialize;
Expand Down Expand Up @@ -189,3 +189,19 @@ where
let ser = Serializer::new();
value.serialize(ser)
}

/// Encode a `T` Serializable into a BSON `Document`.
pub fn to_document<T: ?Sized>(value: &T) -> Result<Document>
where
T: Serialize,
{
match to_bson(value)? {
Bson::Document(doc) => Ok(doc),
bson => Err(Error::SerializationError {
message: format!(
"Could not be serialized to Document, got {:?} instead",
bson.element_type()
),
}),
}
}
6 changes: 4 additions & 2 deletions src/tests/modules/ser.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use std::{collections::BTreeMap, u16, u32, u64, u8};

use assert_matches::assert_matches;

#[cfg(feature = "decimal128")]
use crate::decimal128::Decimal128;
use crate::{from_bson, oid::ObjectId, ser, tests::LOCK, to_bson, Bson};
use assert_matches::assert_matches;
use std::{collections::BTreeMap, u16, u32, u64, u8};

#[test]
#[allow(clippy::float_cmp)]
Expand Down
55 changes: 55 additions & 0 deletions src/tests/modules/serializer_deserializer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,18 @@ use std::{
io::{Cursor, Write},
};

use serde::{Deserialize, Serialize};

#[cfg(feature = "decimal128")]
use crate::decimal128::Decimal128;
use crate::{
de::from_document,
doc,
oid::ObjectId,
ser::Error,
spec::BinarySubtype,
tests::LOCK,
to_document,
Binary,
Bson,
Document,
Expand Down Expand Up @@ -470,3 +475,53 @@ fn test_serialize_deserialize_db_pointer() {
let deserialized = Document::from_reader(&mut Cursor::new(buf)).unwrap();
assert_eq!(deserialized, doc);
}

#[test]
fn test_serialize_deserialize_document() {
let _guard = LOCK.run_concurrently();

#[derive(Debug, Deserialize, Serialize, PartialEq)]
struct Point {
x: i32,
y: i32,
}
let src = Point { x: 1, y: 2 };

let doc = to_document(&src).unwrap();
assert_eq!(doc, doc! { "x": 1, "y": 2 });

let point: Point = from_document(doc).unwrap();
assert_eq!(src, point);

#[derive(Debug, Deserialize, Serialize, PartialEq)]
struct Line {
p1: Point,
p2: Point,
}
let src = Line {
p1: Point { x: 0, y: 0 },
p2: Point { x: 1, y: 1 },
};

let doc = to_document(&src).unwrap();
assert_eq!(
doc,
doc! { "p1": { "x": 0, "y": 0 }, "p2": { "x": 1, "y": 1 } }
);

let line: Line = from_document(doc).unwrap();
assert_eq!(src, line);

let x = 1;
let err = to_document(&x).unwrap_err();
match err {
Error::SerializationError { message } => {
assert!(message.contains("Could not be serialized to Document"));
}
e => panic!("expected SerializationError, got {}", e),
}

let bad_point = doc! { "x": "one", "y": "two" };
let bad_point: Result<Point, crate::de::Error> = from_document(bad_point);
assert!(bad_point.is_err());
}