1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
use bson;
use bson::{ Bson, Document, ValueAccessError };
use serde::{ Serialize, Deserialize };
use error::{ Error, Result, ResultExt };
pub trait BsonExt: Sized {
fn try_into_doc(self) -> Result<Document>;
fn try_as_bool(&self) -> Option<bool>;
}
impl BsonExt for Bson {
fn try_into_doc(self) -> Result<Document> {
match self {
Bson::Document(doc) => Ok(doc),
value => Err(Error::with_cause(
format!("expected Document, got {:?}", value.element_type()),
ValueAccessError::UnexpectedType,
))
}
}
#[cfg_attr(feature = "cargo-clippy", allow(float_cmp))]
fn try_as_bool(&self) -> Option<bool> {
match *self {
Bson::Boolean(b) => Some(b),
Bson::I32(0) | Bson::I64(0) => Some(false),
Bson::I32(1) | Bson::I64(1) => Some(true),
Bson::FloatingPoint(x) if x == 0.0 => Some(false),
Bson::FloatingPoint(x) if x == 1.0 => Some(true),
_ => None,
}
}
}
pub fn serialize_document<T: Serialize>(value: &T) -> Result<Document> {
bson::to_bson(value).chain("BSON serialization error").and_then(Bson::try_into_doc)
}
pub fn serialize_documents<T: Serialize>(values: &[T]) -> Result<Vec<Document>> {
values.iter().map(serialize_document).collect()
}
pub fn deserialize_document<T>(doc: Document) -> Result<T>
where T: for<'a> Deserialize<'a>
{
bson::from_bson(doc.into()).chain("can't deserialize document from BSON")
}
pub fn deserialize_documents<T>(docs: Vec<Document>) -> Result<Vec<T>>
where T: for<'a> Deserialize<'a>
{
docs.into_iter().map(deserialize_document).collect()
}