Debian Codegraph @

src/extjson/de.rs

raw
1 //! Deserializing [MongoDB Extended JSON v2](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json/)
2 //!
3 //! ## Usage
4 //!
5 //! Extended JSON can be deserialized using [`Bson`](../../enum.Bson.html)'s
6 //! `TryFrom<serde_json::Value>` implementation. This implementation accepts both canonical and
7 //! relaxed extJSON, and the two modes can even be mixed within a single representation.
8 //!
9 //! e.g.
10 //! ```rust
11 //! # use bson::Bson;
12 //! # use serde_json::json;
13 //! # use std::convert::{TryFrom, TryInto};
14 //! let json_doc = json!({ "x": 5i32, "y": { "$numberInt": "5" }, "z": { "subdoc": "hello" } });
15 //! let bson: Bson = json_doc.try_into().unwrap(); // Bson::Document(...)
16 //!
17 //! let json_date = json!({ "$date": { "$numberLong": "1590972160292" } });
18 //! let bson_date: Bson = json_date.try_into().unwrap(); // Bson::DateTime(...)
19 //!
20 //! let invalid_ext_json = json!({ "$numberLong": 5 });
21 //! Bson::try_from(invalid_ext_json).expect_err("5 should be a string");
22 //! ```
23
24 use std::convert::{TryFrom, TryInto};
25
26 use serde::de::{Error as _, Unexpected};
27
28 use crate::{extjson::models, oid, Bson, Document};
29
30 #[derive(Clone, Debug)]
31 #[non_exhaustive]
32 /// Error cases that can occur during deserialization from [extended JSON](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json/).
33 pub enum Error {
34 /// Errors that can occur during OID construction and generation from the input data.
35 InvalidObjectId(oid::Error),
36
37 /// A general error encountered during deserialization.
38 /// See: <https://docs.serde.rs/serde/de/trait.Error.html>
39 DeserializationError { message: String },
40 }
41
42 impl std::fmt::Display for Error {
43 fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
44 match *self {
45 Self::InvalidObjectId(ref err) => err.fmt(fmt),
46 Self::DeserializationError { ref message } => message.fmt(fmt),
47 }
48 }
49 }
50
51 impl std::error::Error for Error {}
52
53 impl serde::de::Error for Error {
54 fn custom<T>(msg: T) -> Self
55 where
56 T: std::fmt::Display,
57 {
58 Self::DeserializationError {
59 message: format!("{}", msg),
60 }
61 }
62 }
63
64 impl From<serde_json::Error> for Error {
65 fn from(err: serde_json::Error) -> Self {
66 Self::DeserializationError {
67 message: err.to_string(),
68 }
69 }
70 }
71
72 impl From<oid::Error> for Error {
73 fn from(err: oid::Error) -> Self {
74 Self::InvalidObjectId(err)
75 }
76 }
77
78 pub type Result<T> = std::result::Result<T, Error>;
79
80 /// This converts from the input JSON object as if it were [MongoDB Extended JSON v2](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json/).
81 impl TryFrom<serde_json::Map<String, serde_json::Value>> for Bson {
82 type Error = Error;
83
84 fn try_from(obj: serde_json::Map<String, serde_json::Value>) -> Result<Self> {
85 if obj.contains_key("$oid") {
86 let oid: models::ObjectId = serde_json::from_value(obj.into())?;
87 return Ok(Bson::ObjectId(oid.parse()?));
88 }
89
90 if obj.contains_key("$symbol") {
91 let symbol: models::Symbol = serde_json::from_value(obj.into())?;
92 return Ok(Bson::Symbol(symbol.value));
93 }
94
95 if obj.contains_key("$regularExpression") {
96 let regex: models::Regex = serde_json::from_value(obj.into())?;
97 return Ok(regex.parse().into());
98 }
99
100 if obj.contains_key("$numberInt") {
101 let int: models::Int32 = serde_json::from_value(obj.into())?;
102 return Ok(Bson::Int32(int.parse()?));
103 }
104
105 if obj.contains_key("$numberLong") {
106 let int: models::Int64 = serde_json::from_value(obj.into())?;
107 return Ok(Bson::Int64(int.parse()?));
108 }
109
110 if obj.contains_key("$numberDouble") {
111 let double: models::Double = serde_json::from_value(obj.into())?;
112 return Ok(Bson::Double(double.parse()?));
113 }
114
115 if obj.contains_key("$numberDecimal") {
116 let decimal: models::Decimal128 = serde_json::from_value(obj.into())?;
117 return Ok(Bson::Decimal128(decimal.parse()?));
118 }
119
120 if obj.contains_key("$binary") {
121 let binary: models::Binary = serde_json::from_value(obj.into())?;
122 return Ok(Bson::Binary(binary.parse()?));
123 }
124
125 if obj.contains_key("$uuid") {
126 let uuid: models::Uuid = serde_json::from_value(obj.into())?;
127 return Ok(Bson::Binary(uuid.parse()?));
128 }
129
130 if obj.contains_key("$code") {
131 let code_w_scope: models::JavaScriptCodeWithScope = serde_json::from_value(obj.into())?;
132 return match code_w_scope.scope {
133 Some(scope) => Ok(crate::JavaScriptCodeWithScope {
134 code: code_w_scope.code,
135 scope: scope.try_into()?,
136 }
137 .into()),
138 None => Ok(Bson::JavaScriptCode(code_w_scope.code)),
139 };
140 }
141
142 if obj.contains_key("$timestamp") {
143 let ts: models::Timestamp = serde_json::from_value(obj.into())?;
144 return Ok(ts.parse().into());
145 }
146
147 if obj.contains_key("$date") {
148 let extjson_datetime: models::DateTime = serde_json::from_value(obj.into())?;
149 return Ok(Bson::DateTime(extjson_datetime.parse()?));
150 }
151
152 if obj.contains_key("$minKey") {
153 let min_key: models::MinKey = serde_json::from_value(obj.into())?;
154 return min_key.parse();
155 }
156
157 if obj.contains_key("$maxKey") {
158 let max_key: models::MaxKey = serde_json::from_value(obj.into())?;
159 return max_key.parse();
160 }
161
162 if obj.contains_key("$dbPointer") {
163 let db_ptr: models::DbPointer = serde_json::from_value(obj.into())?;
164 return Ok(db_ptr.parse()?.into());
165 }
166
167 if obj.contains_key("$undefined") {
168 let undefined: models::Undefined = serde_json::from_value(obj.into())?;
169 return undefined.parse();
170 }
171
172 Ok(Bson::Document(obj.try_into()?))
173 }
174 }
175
176 /// This converts from the input JSON as if it were [MongoDB Extended JSON v2](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json/).
177 impl TryFrom<serde_json::Value> for Bson {
178 type Error = Error;
179
180 fn try_from(value: serde_json::Value) -> Result<Self> {
181 match value {
182 serde_json::Value::Number(x) => x
183 .as_i64()
184 .map(|i| {
185 if i >= std::i32::MIN as i64 && i <= std::i32::MAX as i64 {
186 Bson::Int32(i as i32)
187 } else {
188 Bson::Int64(i)
189 }
190 })
191 .or_else(|| x.as_f64().map(Bson::from))
192 .ok_or_else(|| {
193 Error::invalid_value(
194 Unexpected::Other(format!("{}", x).as_str()),
195 &"a number that could fit in i32, i64, or f64",
196 )
197 }),
198 serde_json::Value::String(x) => Ok(x.into()),
199 serde_json::Value::Bool(x) => Ok(x.into()),
200 serde_json::Value::Array(x) => Ok(Bson::Array(
201 x.into_iter()
202 .map(Bson::try_from)
203 .collect::<Result<Vec<Bson>>>()?,
204 )),
205 serde_json::Value::Null => Ok(Bson::Null),
206 serde_json::Value::Object(map) => map.try_into(),
207 }
208 }
209 }
210
211 /// This converts from the input JSON as if it were [MongoDB Extended JSON v2](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json/).
212 impl TryFrom<serde_json::Map<String, serde_json::Value>> for Document {
213 type Error = Error;
214
215 fn try_from(obj: serde_json::Map<String, serde_json::Value>) -> Result<Self> {
216 Ok(obj
217 .into_iter()
218 .map(|(k, v)| -> Result<(String, Bson)> {
219 let value: Bson = v.try_into()?;
220 Ok((k, value))
221 })
222 .collect::<Result<Vec<(String, Bson)>>>()?
223 .into_iter()
224 .collect())
225 }
226 }