Skip to content

Commit 2ff3d05

Browse files
committed
RUST-806 Allow conversion of Options to Bson types
1 parent 2e6bb8f commit 2ff3d05

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

src/bson.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,18 @@ impl From<DbPointer> for Bson {
304304
}
305305
}
306306

307+
impl<T> From<Option<T>> for Bson
308+
where
309+
T: Into<Bson>,
310+
{
311+
fn from(a: Option<T>) -> Bson {
312+
match a {
313+
None => Bson::Null,
314+
Some(t) => t.into(),
315+
}
316+
}
317+
}
318+
307319
/// This will create the [relaxed Extended JSON v2](https://docs.mongodb.com/manual/reference/mongodb-extended-json/) representation of the provided [`Bson`](../enum.Bson.html).
308320
impl From<Bson> for Value {
309321
fn from(bson: Bson) -> Self {

src/tests/modules/bson.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,17 @@ fn from_impls() {
143143
Bson::Document(doc! {"a": "b"})
144144
);
145145

146+
// Optionals
147+
assert_eq!(Bson::from(Some(4)), Bson::Int32(4));
148+
assert_eq!(
149+
Bson::from(Some(String::from("data"))),
150+
Bson::String(String::from("data"))
151+
);
152+
assert_eq!(Bson::from(None::<i32>), Bson::Null);
153+
assert_eq!(Bson::from(None::<String>), Bson::Null);
154+
assert_eq!(doc! {"x": Some(4)}, doc! {"x": 4});
155+
assert_eq!(doc! {"x": None::<i32>}, doc! {"x": Bson::Null});
156+
146157
let db_pointer = Bson::try_from(json!({
147158
"$dbPointer": {
148159
"$ref": "db.coll",

0 commit comments

Comments
 (0)