Debian Codegraph @

src/bson.rs

raw
1 // The MIT License (MIT)
2
3 // Copyright (c) 2015 Y. T. Chung <[email protected]>
4
5 // Permission is hereby granted, free of charge, to any person obtaining a copy of
6 // this software and associated documentation files (the "Software"), to deal in
7 // the Software without restriction, including without limitation the rights to
8 // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 // the Software, and to permit persons to whom the Software is furnished to do so,
10 // subject to the following conditions:
11
12 // The above copyright notice and this permission notice shall be included in all
13 // copies or substantial portions of the Software.
14
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22 //! BSON definition
23
24 use std::{
25 convert::{TryFrom, TryInto},
26 fmt::{self, Debug, Display, Formatter},
27 };
28
29 use serde_json::{json, Value};
30
31 pub use crate::document::Document;
32 use crate::{
33 oid::{self, ObjectId},
34 spec::{BinarySubtype, ElementType},
35 Binary,
36 Decimal128,
37 };
38
39 /// Possible BSON value types.
40 #[derive(Clone, Default, PartialEq)]
41 pub enum Bson {
42 /// 64-bit binary floating point
43 Double(f64),
44 /// UTF-8 string
45 String(String),
46 /// Array
47 Array(Array),
48 /// Embedded document
49 Document(Document),
50 /// Boolean value
51 Boolean(bool),
52 /// Null value
53 #[default]
54 Null,
55 /// Regular expression
56 RegularExpression(Regex),
57 /// JavaScript code
58 JavaScriptCode(String),
59 /// JavaScript code w/ scope
60 JavaScriptCodeWithScope(JavaScriptCodeWithScope),
61 /// 32-bit signed integer
62 Int32(i32),
63 /// 64-bit signed integer
64 Int64(i64),
65 /// Timestamp
66 Timestamp(Timestamp),
67 /// Binary data
68 Binary(Binary),
69 /// [ObjectId](http://dochub.mongodb.org/core/objectids)
70 ObjectId(oid::ObjectId),
71 /// UTC datetime
72 DateTime(crate::DateTime),
73 /// Symbol (Deprecated)
74 Symbol(String),
75 /// [128-bit decimal floating point](https://github.com/mongodb/specifications/blob/master/source/bson-decimal128/decimal128.rst)
76 Decimal128(Decimal128),
77 /// Undefined value (Deprecated)
78 Undefined,
79 /// Max key
80 MaxKey,
81 /// Min key
82 MinKey,
83 /// DBPointer (Deprecated)
84 DbPointer(DbPointer),
85 }
86
87 /// Alias for `Vec<Bson>`.
88 pub type Array = Vec<Bson>;
89
90 impl Display for Bson {
91 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
92 match *self {
93 Bson::Double(f) => write!(fmt, "{}", f),
94 Bson::String(ref s) => write!(fmt, "\"{}\"", s),
95 Bson::Array(ref vec) => {
96 fmt.write_str("[")?;
97
98 let mut first = true;
99 for bson in vec {
100 if !first {
101 fmt.write_str(", ")?;
102 }
103
104 write!(fmt, "{}", bson)?;
105 first = false;
106 }
107
108 fmt.write_str("]")
109 }
110 Bson::Document(ref doc) => write!(fmt, "{}", doc),
111 Bson::Boolean(b) => write!(fmt, "{}", b),
112 Bson::Null => write!(fmt, "null"),
113 Bson::RegularExpression(ref x) => write!(fmt, "{}", x),
114 Bson::JavaScriptCode(ref code)
115 | Bson::JavaScriptCodeWithScope(JavaScriptCodeWithScope { ref code, .. }) => {
116 fmt.write_str(code)
117 }
118 Bson::Int32(i) => write!(fmt, "{}", i),
119 Bson::Int64(i) => write!(fmt, "{}", i),
120 Bson::Timestamp(ref x) => write!(fmt, "{}", x),
121 Bson::Binary(ref x) => write!(fmt, "{}", x),
122 Bson::ObjectId(ref id) => write!(fmt, "ObjectId(\"{}\")", id),
123 Bson::DateTime(date_time) => write!(fmt, "DateTime(\"{}\")", date_time),
124 Bson::Symbol(ref sym) => write!(fmt, "Symbol(\"{}\")", sym),
125 Bson::Decimal128(ref d) => write!(fmt, "{}", d),
126 Bson::Undefined => write!(fmt, "undefined"),
127 Bson::MinKey => write!(fmt, "MinKey"),
128 Bson::MaxKey => write!(fmt, "MaxKey"),
129 Bson::DbPointer(DbPointer {
130 ref namespace,
131 ref id,
132 }) => write!(fmt, "DbPointer({}, {})", namespace, id),
133 }
134 }
135 }
136
137 impl Debug for Bson {
138 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
139 match *self {
140 Bson::Double(f) => fmt.debug_tuple("Double").field(&f).finish(),
141 Bson::String(ref s) => fmt.debug_tuple("String").field(s).finish(),
142 Bson::Array(ref vec) => {
143 write!(fmt, "Array(")?;
144 Debug::fmt(vec, fmt)?;
145 write!(fmt, ")")
146 }
147 Bson::Document(ref doc) => Debug::fmt(doc, fmt),
148 Bson::Boolean(b) => fmt.debug_tuple("Boolean").field(&b).finish(),
149 Bson::Null => write!(fmt, "Null"),
150 Bson::RegularExpression(ref regex) => Debug::fmt(regex, fmt),
151 Bson::JavaScriptCode(ref code) => {
152 fmt.debug_tuple("JavaScriptCode").field(code).finish()
153 }
154 Bson::JavaScriptCodeWithScope(ref code) => Debug::fmt(code, fmt),
155 Bson::Int32(i) => fmt.debug_tuple("Int32").field(&i).finish(),
156 Bson::Int64(i) => fmt.debug_tuple("Int64").field(&i).finish(),
157 Bson::Timestamp(ref t) => Debug::fmt(t, fmt),
158 Bson::Binary(ref b) => Debug::fmt(b, fmt),
159 Bson::ObjectId(ref id) => Debug::fmt(id, fmt),
160 Bson::DateTime(ref date_time) => Debug::fmt(date_time, fmt),
161 Bson::Symbol(ref sym) => fmt.debug_tuple("Symbol").field(sym).finish(),
162 Bson::Decimal128(ref d) => Debug::fmt(d, fmt),
163 Bson::Undefined => write!(fmt, "Undefined"),
164 Bson::MinKey => write!(fmt, "MinKey"),
165 Bson::MaxKey => write!(fmt, "MaxKey"),
166 Bson::DbPointer(ref pointer) => Debug::fmt(pointer, fmt),
167 }
168 }
169 }
170
171 impl From<f32> for Bson {
172 fn from(a: f32) -> Bson {
173 Bson::Double(a.into())
174 }
175 }
176
177 impl From<f64> for Bson {
178 fn from(a: f64) -> Bson {
179 Bson::Double(a)
180 }
181 }
182
183 impl From<&str> for Bson {
184 fn from(s: &str) -> Bson {
185 Bson::String(s.to_owned())
186 }
187 }
188
189 impl From<String> for Bson {
190 fn from(a: String) -> Bson {
191 Bson::String(a)
192 }
193 }
194
195 impl From<Document> for Bson {
196 fn from(a: Document) -> Bson {
197 Bson::Document(a)
198 }
199 }
200
201 impl From<bool> for Bson {
202 fn from(a: bool) -> Bson {
203 Bson::Boolean(a)
204 }
205 }
206
207 impl From<Regex> for Bson {
208 fn from(regex: Regex) -> Bson {
209 Bson::RegularExpression(regex)
210 }
211 }
212
213 impl From<JavaScriptCodeWithScope> for Bson {
214 fn from(code_with_scope: JavaScriptCodeWithScope) -> Bson {
215 Bson::JavaScriptCodeWithScope(code_with_scope)
216 }
217 }
218
219 impl From<Binary> for Bson {
220 fn from(binary: Binary) -> Bson {
221 Bson::Binary(binary)
222 }
223 }
224
225 impl From<Timestamp> for Bson {
226 fn from(ts: Timestamp) -> Bson {
227 Bson::Timestamp(ts)
228 }
229 }
230
231 impl<T> From<&T> for Bson
232 where
233 T: Clone + Into<Bson>,
234 {
235 fn from(t: &T) -> Bson {
236 t.clone().into()
237 }
238 }
239
240 impl<T> From<&mut T> for Bson
241 where
242 for<'a> &'a T: Into<Bson>,
243 {
244 fn from(t: &mut T) -> Bson {
245 (&*t).into()
246 }
247 }
248
249 impl<T> From<Vec<T>> for Bson
250 where
251 T: Into<Bson>,
252 {
253 fn from(v: Vec<T>) -> Bson {
254 Bson::Array(v.into_iter().map(|val| val.into()).collect())
255 }
256 }
257
258 impl<T> From<&[T]> for Bson
259 where
260 T: Clone + Into<Bson>,
261 {
262 fn from(s: &[T]) -> Bson {
263 Bson::Array(s.iter().cloned().map(|val| val.into()).collect())
264 }
265 }
266
267 impl<T: Into<Bson>> ::std::iter::FromIterator<T> for Bson {
268 /// # Examples
269 ///
270 /// ```
271 /// use std::iter::FromIterator;
272 /// use bson::Bson;
273 ///
274 /// let x: Bson = Bson::from_iter(vec!["lorem", "ipsum", "dolor"]);
275 /// // or
276 /// let x: Bson = vec!["lorem", "ipsum", "dolor"].into_iter().collect();
277 /// ```
278 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
279 Bson::Array(iter.into_iter().map(Into::into).collect())
280 }
281 }
282
283 impl From<i32> for Bson {
284 fn from(a: i32) -> Bson {
285 Bson::Int32(a)
286 }
287 }
288
289 impl From<i64> for Bson {
290 fn from(a: i64) -> Bson {
291 Bson::Int64(a)
292 }
293 }
294
295 impl From<u32> for Bson {
296 fn from(a: u32) -> Bson {
297 if let Ok(i) = i32::try_from(a) {
298 Bson::Int32(i)
299 } else {
300 Bson::Int64(a.into())
301 }
302 }
303 }
304
305 impl From<[u8; 12]> for Bson {
306 fn from(a: [u8; 12]) -> Bson {
307 Bson::ObjectId(oid::ObjectId::from_bytes(a))
308 }
309 }
310
311 impl From<oid::ObjectId> for Bson {
312 fn from(a: oid::ObjectId) -> Bson {
313 Bson::ObjectId(a)
314 }
315 }
316
317 #[cfg(feature = "time-0_3")]
318 #[cfg_attr(docsrs, doc(cfg(feature = "time-0_3")))]
319 impl From<time::OffsetDateTime> for Bson {
320 fn from(a: time::OffsetDateTime) -> Bson {
321 Bson::DateTime(crate::DateTime::from(a))
322 }
323 }
324
325 #[cfg(feature = "chrono-0_4")]
326 #[cfg_attr(docsrs, doc(cfg(feature = "chrono-0_4")))]
327 impl<T: chrono::TimeZone> From<chrono::DateTime<T>> for Bson {
328 fn from(a: chrono::DateTime<T>) -> Bson {
329 Bson::DateTime(crate::DateTime::from(a))
330 }
331 }
332
333 #[cfg(feature = "uuid-0_8")]
334 #[cfg_attr(docsrs, doc(cfg(feature = "uuid-0_8")))]
335 impl From<uuid_0_8::Uuid> for Bson {
336 fn from(uuid: uuid_0_8::Uuid) -> Self {
337 Bson::Binary(uuid.into())
338 }
339 }
340
341 #[cfg(feature = "uuid-1")]
342 #[cfg_attr(docsrs, doc(cfg(feature = "uuid-1")))]
343 impl From<uuid::Uuid> for Bson {
344 fn from(uuid: uuid::Uuid) -> Self {
345 Bson::Binary(uuid.into())
346 }
347 }
348
349 impl From<crate::DateTime> for Bson {
350 fn from(dt: crate::DateTime) -> Self {
351 Bson::DateTime(dt)
352 }
353 }
354
355 impl From<DbPointer> for Bson {
356 fn from(a: DbPointer) -> Bson {
357 Bson::DbPointer(a)
358 }
359 }
360
361 impl From<Decimal128> for Bson {
362 fn from(d: Decimal128) -> Self {
363 Bson::Decimal128(d)
364 }
365 }
366
367 impl<T> From<Option<T>> for Bson
368 where
369 T: Into<Bson>,
370 {
371 fn from(a: Option<T>) -> Bson {
372 match a {
373 None => Bson::Null,
374 Some(t) => t.into(),
375 }
376 }
377 }
378
379 /// This will create the [relaxed Extended JSON v2](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json/) representation of the provided [`Bson`](../enum.Bson.html).
380 impl From<Bson> for Value {
381 fn from(bson: Bson) -> Self {
382 bson.into_relaxed_extjson()
383 }
384 }
385
386 impl Bson {
387 /// Converts the Bson value into its [relaxed extended JSON representation](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json/).
388 ///
389 /// Note: If this method is called on a case which contains a `Decimal128` value, it will panic.
390 pub fn into_relaxed_extjson(self) -> Value {
391 match self {
392 Bson::Double(v) if v.is_nan() => {
393 let s = if v.is_sign_negative() { "-NaN" } else { "NaN" };
394
395 json!({ "$numberDouble": s })
396 }
397 Bson::Double(v) if v.is_infinite() => {
398 let s = if v.is_sign_negative() {
399 "-Infinity"
400 } else {
401 "Infinity"
402 };
403
404 json!({ "$numberDouble": s })
405 }
406 Bson::Double(v) => json!(v),
407 Bson::String(v) => json!(v),
408 Bson::Array(v) => Value::Array(v.into_iter().map(Bson::into_relaxed_extjson).collect()),
409 Bson::Document(v) => Value::Object(
410 v.into_iter()
411 .map(|(k, v)| (k, v.into_relaxed_extjson()))
412 .collect(),
413 ),
414 Bson::Boolean(v) => json!(v),
415 Bson::Null => Value::Null,
416 Bson::RegularExpression(Regex { pattern, options }) => {
417 let mut chars: Vec<_> = options.chars().collect();
418 chars.sort_unstable();
419
420 let options: String = chars.into_iter().collect();
421
422 json!({
423 "$regularExpression": {
424 "pattern": pattern,
425 "options": options,
426 }
427 })
428 }
429 Bson::JavaScriptCode(code) => json!({ "$code": code }),
430 Bson::JavaScriptCodeWithScope(JavaScriptCodeWithScope { code, scope }) => json!({
431 "$code": code,
432 "$scope": scope,
433 }),
434 Bson::Int32(v) => v.into(),
435 Bson::Int64(v) => v.into(),
436 Bson::Timestamp(Timestamp { time, increment }) => json!({
437 "$timestamp": {
438 "t": time,
439 "i": increment,
440 }
441 }),
442 Bson::Binary(Binary { subtype, ref bytes }) => {
443 let tval: u8 = From::from(subtype);
444 json!({
445 "$binary": {
446 "base64": base64::encode(bytes),
447 "subType": hex::encode([tval]),
448 }
449 })
450 }
451 Bson::ObjectId(v) => json!({"$oid": v.to_hex()}),
452 Bson::DateTime(v) if v.timestamp_millis() >= 0 && v.to_time_0_3().year() <= 9999 => {
453 json!({
454 // Unwrap safety: timestamps in the guarded range can always be formatted.
455 "$date": v.try_to_rfc3339_string().unwrap(),
456 })
457 }
458 Bson::DateTime(v) => json!({
459 "$date": { "$numberLong": v.timestamp_millis().to_string() },
460 }),
461 Bson::Symbol(v) => json!({ "$symbol": v }),
462 Bson::Decimal128(v) => json!({ "$numberDecimal": v.to_string() }),
463 Bson::Undefined => json!({ "$undefined": true }),
464 Bson::MinKey => json!({ "$minKey": 1 }),
465 Bson::MaxKey => json!({ "$maxKey": 1 }),
466 Bson::DbPointer(DbPointer {
467 ref namespace,
468 ref id,
469 }) => json!({
470 "$dbPointer": {
471 "$ref": namespace,
472 "$id": {
473 "$oid": id.to_hex()
474 }
475 }
476 }),
477 }
478 }
479
480 /// Converts the Bson value into its [canonical extended JSON representation](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json/).
481 pub fn into_canonical_extjson(self) -> Value {
482 match self {
483 Bson::Int32(i) => json!({ "$numberInt": i.to_string() }),
484 Bson::Int64(i) => json!({ "$numberLong": i.to_string() }),
485 Bson::Double(f) if f.is_normal() => {
486 let mut s = f.to_string();
487 if f.fract() == 0.0 {
488 s.push_str(".0");
489 }
490
491 json!({ "$numberDouble": s })
492 }
493 Bson::Double(f) if f == 0.0 => {
494 let s = if f.is_sign_negative() { "-0.0" } else { "0.0" };
495
496 json!({ "$numberDouble": s })
497 }
498 Bson::DateTime(date) => {
499 json!({ "$date": { "$numberLong": date.timestamp_millis().to_string() } })
500 }
501 Bson::Array(arr) => {
502 Value::Array(arr.into_iter().map(Bson::into_canonical_extjson).collect())
503 }
504 Bson::Document(arr) => Value::Object(
505 arr.into_iter()
506 .map(|(k, v)| (k, v.into_canonical_extjson()))
507 .collect(),
508 ),
509 Bson::JavaScriptCodeWithScope(JavaScriptCodeWithScope { code, scope }) => json!({
510 "$code": code,
511 "$scope": Bson::Document(scope).into_canonical_extjson(),
512 }),
513
514 other => other.into_relaxed_extjson(),
515 }
516 }
517
518 /// Get the [`ElementType`] of this value.
519 pub fn element_type(&self) -> ElementType {
520 match *self {
521 Bson::Double(..) => ElementType::Double,
522 Bson::String(..) => ElementType::String,
523 Bson::Array(..) => ElementType::Array,
524 Bson::Document(..) => ElementType::EmbeddedDocument,
525 Bson::Boolean(..) => ElementType::Boolean,
526 Bson::Null => ElementType::Null,
527 Bson::RegularExpression(..) => ElementType::RegularExpression,
528 Bson::JavaScriptCode(..) => ElementType::JavaScriptCode,
529 Bson::JavaScriptCodeWithScope(..) => ElementType::JavaScriptCodeWithScope,
530 Bson::Int32(..) => ElementType::Int32,
531 Bson::Int64(..) => ElementType::Int64,
532 Bson::Timestamp(..) => ElementType::Timestamp,
533 Bson::Binary(..) => ElementType::Binary,
534 Bson::ObjectId(..) => ElementType::ObjectId,
535 Bson::DateTime(..) => ElementType::DateTime,
536 Bson::Symbol(..) => ElementType::Symbol,
537 Bson::Decimal128(..) => ElementType::Decimal128,
538 Bson::Undefined => ElementType::Undefined,
539 Bson::MaxKey => ElementType::MaxKey,
540 Bson::MinKey => ElementType::MinKey,
541 Bson::DbPointer(..) => ElementType::DbPointer,
542 }
543 }
544
545 /// Converts to extended format.
546 /// This function mainly used for [extended JSON format](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json/).
547 // TODO RUST-426: Investigate either removing this from the serde implementation or unifying
548 // with the extended JSON implementation.
549 pub(crate) fn into_extended_document(self, rawbson: bool) -> Document {
550 match self {
551 Bson::RegularExpression(Regex {
552 ref pattern,
553 ref options,
554 }) => {
555 let mut chars: Vec<_> = options.chars().collect();
556 chars.sort_unstable();
557
558 let options: String = chars.into_iter().collect();
559
560 doc! {
561 "$regularExpression": {
562 "pattern": pattern,
563 "options": options,
564 }
565 }
566 }
567 Bson::JavaScriptCode(ref code) => {
568 doc! {
569 "$code": code,
570 }
571 }
572 Bson::JavaScriptCodeWithScope(JavaScriptCodeWithScope { code, scope }) => {
573 doc! {
574 "$code": code,
575 "$scope": scope,
576 }
577 }
578 Bson::Timestamp(Timestamp { time, increment }) => {
579 doc! {
580 "$timestamp": {
581 "t": time,
582 "i": increment,
583 }
584 }
585 }
586 Bson::Binary(Binary { subtype, bytes }) => {
587 let tval: u8 = From::from(subtype);
588 if rawbson {
589 doc! {
590 "$binary": {
591 "bytes": Binary { subtype: BinarySubtype::Generic, bytes },
592 "subType": Bson::Int32(tval.into())
593 }
594 }
595 } else {
596 doc! {
597 "$binary": {
598 "base64": base64::encode(bytes),
599 "subType": hex::encode([tval]),
600 }
601 }
602 }
603 }
604 Bson::ObjectId(ref v) => {
605 doc! {
606 "$oid": v.to_string(),
607 }
608 }
609 Bson::DateTime(v) if rawbson => doc! {
610 "$date": v.timestamp_millis(),
611 },
612 Bson::DateTime(v) if v.timestamp_millis() >= 0 && v.to_time_0_3().year() <= 9999 => {
613 doc! {
614 // Unwrap safety: timestamps in the guarded range can always be formatted.
615 "$date": v.try_to_rfc3339_string().unwrap(),
616 }
617 }
618 Bson::DateTime(v) => doc! {
619 "$date": { "$numberLong": v.timestamp_millis().to_string() },
620 },
621 Bson::Symbol(ref v) => {
622 doc! {
623 "$symbol": v.to_owned(),
624 }
625 }
626 Bson::Undefined => {
627 doc! {
628 "$undefined": true,
629 }
630 }
631 Bson::MinKey => {
632 doc! {
633 "$minKey": 1,
634 }
635 }
636 Bson::MaxKey => {
637 doc! {
638 "$maxKey": 1,
639 }
640 }
641 Bson::DbPointer(DbPointer {
642 ref namespace,
643 ref id,
644 }) => {
645 doc! {
646 "$dbPointer": {
647 "$ref": namespace,
648 "$id": {
649 "$oid": id.to_string()
650 }
651 }
652 }
653 }
654 _ => panic!("Attempted conversion of invalid data type: {}", self),
655 }
656 }
657
658 pub(crate) fn from_extended_document(doc: Document) -> Bson {
659 if doc.len() > 2 {
660 return Bson::Document(doc);
661 }
662
663 let mut keys: Vec<_> = doc.keys().map(|s| s.as_str()).collect();
664 keys.sort_unstable();
665
666 match keys.as_slice() {
667 ["$oid"] => {
668 if let Ok(oid) = doc.get_str("$oid") {
669 if let Ok(oid) = ObjectId::parse_str(oid) {
670 return Bson::ObjectId(oid);
671 }
672 }
673 }
674
675 ["$symbol"] => {
676 if let Ok(symbol) = doc.get_str("$symbol") {
677 return Bson::Symbol(symbol.into());
678 }
679 }
680
681 ["$numberInt"] => {
682 if let Ok(i) = doc.get_str("$numberInt") {
683 if let Ok(i) = i.parse() {
684 return Bson::Int32(i);
685 }
686 }
687 }
688
689 ["$numberLong"] => {
690 if let Ok(i) = doc.get_str("$numberLong") {
691 if let Ok(i) = i.parse() {
692 return Bson::Int64(i);
693 }
694 }
695 }
696
697 ["$numberDouble"] => match doc.get_str("$numberDouble") {
698 Ok("Infinity") => return Bson::Double(std::f64::INFINITY),
699 Ok("-Infinity") => return Bson::Double(std::f64::NEG_INFINITY),
700 Ok("NaN") => return Bson::Double(std::f64::NAN),
701 Ok(other) => {
702 if let Ok(d) = other.parse() {
703 return Bson::Double(d);
704 }
705 }
706 _ => {}
707 },
708
709 ["$numberDecimal"] => {
710 if let Ok(d) = doc.get_str("$numberDecimal") {
711 if let Ok(d) = d.parse() {
712 return Bson::Decimal128(d);
713 }
714 }
715 }
716
717 ["$numberDecimalBytes"] => {
718 if let Ok(bytes) = doc.get_binary_generic("$numberDecimalBytes") {
719 if let Ok(b) = bytes.clone().try_into() {
720 return Bson::Decimal128(Decimal128 { bytes: b });
721 }
722 }
723 }
724
725 ["$binary"] => {
726 if let Some(binary) = Binary::from_extended_doc(&doc) {
727 return Bson::Binary(binary);
728 }
729 }
730
731 ["$code"] => {
732 if let Ok(code) = doc.get_str("$code") {
733 return Bson::JavaScriptCode(code.into());
734 }
735 }
736
737 ["$code", "$scope"] => {
738 if let Ok(code) = doc.get_str("$code") {
739 if let Ok(scope) = doc.get_document("$scope") {
740 return Bson::JavaScriptCodeWithScope(JavaScriptCodeWithScope {
741 code: code.into(),
742 scope: scope.clone(),
743 });
744 }
745 }
746 }
747
748 ["$timestamp"] => {
749 if let Ok(timestamp) = doc.get_document("$timestamp") {
750 if let Ok(t) = timestamp.get_i32("t") {
751 if let Ok(i) = timestamp.get_i32("i") {
752 return Bson::Timestamp(Timestamp {
753 time: t as u32,
754 increment: i as u32,
755 });
756 }
757 }
758
759 if let Ok(t) = timestamp.get_i64("t") {
760 if let Ok(i) = timestamp.get_i64("i") {
761 if t >= 0
762 && i >= 0
763 && t <= (std::u32::MAX as i64)
764 && i <= (std::u32::MAX as i64)
765 {
766 return Bson::Timestamp(Timestamp {
767 time: t as u32,
768 increment: i as u32,
769 });
770 }
771 }
772 }
773 }
774 }
775
776 ["$regularExpression"] => {
777 if let Ok(regex) = doc.get_document("$regularExpression") {
778 if let Ok(pattern) = regex.get_str("pattern") {
779 if let Ok(options) = regex.get_str("options") {
780 return Bson::RegularExpression(Regex::new(pattern, options));
781 }
782 }
783 }
784 }
785
786 ["$dbPointer"] => {
787 if let Ok(db_pointer) = doc.get_document("$dbPointer") {
788 if let Ok(ns) = db_pointer.get_str("$ref") {
789 if let Ok(id) = db_pointer.get_object_id("$id") {
790 return Bson::DbPointer(DbPointer {
791 namespace: ns.into(),
792 id,
793 });
794 }
795 }
796 }
797 }
798
799 ["$date"] => {
800 if let Ok(date) = doc.get_i64("$date") {
801 return Bson::DateTime(crate::DateTime::from_millis(date));
802 }
803
804 if let Ok(date) = doc.get_str("$date") {
805 if let Ok(dt) = crate::DateTime::parse_rfc3339_str(date) {
806 return Bson::DateTime(dt);
807 }
808 }
809 }
810
811 ["$minKey"] => {
812 let min_key = doc.get("$minKey");
813
814 if min_key == Some(&Bson::Int32(1)) || min_key == Some(&Bson::Int64(1)) {
815 return Bson::MinKey;
816 }
817 }
818
819 ["$maxKey"] => {
820 let max_key = doc.get("$maxKey");
821
822 if max_key == Some(&Bson::Int32(1)) || max_key == Some(&Bson::Int64(1)) {
823 return Bson::MaxKey;
824 }
825 }
826
827 ["$undefined"] => {
828 if doc.get("$undefined") == Some(&Bson::Boolean(true)) {
829 return Bson::Undefined;
830 }
831 }
832
833 _ => {}
834 };
835
836 Bson::Document(
837 doc.into_iter()
838 .map(|(k, v)| {
839 let v = match v {
840 Bson::Document(v) => Bson::from_extended_document(v),
841 other => other,
842 };
843
844 (k, v)
845 })
846 .collect(),
847 )
848 }
849 }
850
851 /// Value helpers
852 impl Bson {
853 /// If `self` is [`Double`](Bson::Double), return its value as an `f64`. Returns [`None`]
854 /// otherwise.
855 pub fn as_f64(&self) -> Option<f64> {
856 match *self {
857 Bson::Double(v) => Some(v),
858 _ => None,
859 }
860 }
861
862 /// If `self` is [`String`](Bson::String), return its value as a `&str`. Returns [`None`]
863 /// otherwise.
864 pub fn as_str(&self) -> Option<&str> {
865 match *self {
866 Bson::String(ref s) => Some(s),
867 _ => None,
868 }
869 }
870
871 /// If `self` is [`String`](Bson::String), return a mutable reference to its value as a [`str`].
872 /// Returns [`None`] otherwise.
873 pub fn as_str_mut(&mut self) -> Option<&mut str> {
874 match *self {
875 Bson::String(ref mut s) => Some(s),
876 _ => None,
877 }
878 }
879
880 /// If `self` is [`Array`](Bson::Array), return its value. Returns [`None`] otherwise.
881 pub fn as_array(&self) -> Option<&Array> {
882 match *self {
883 Bson::Array(ref v) => Some(v),
884 _ => None,
885 }
886 }
887
888 /// If `self` is [`Array`](Bson::Array), return a mutable reference to its value. Returns
889 /// [`None`] otherwise.
890 pub fn as_array_mut(&mut self) -> Option<&mut Array> {
891 match *self {
892 Bson::Array(ref mut v) => Some(v),
893 _ => None,
894 }
895 }
896
897 /// If `self` is [`Document`](Bson::Document), return its value. Returns [`None`] otherwise.
898 pub fn as_document(&self) -> Option<&Document> {
899 match *self {
900 Bson::Document(ref v) => Some(v),
901 _ => None,
902 }
903 }
904
905 /// If `self` is [`Document`](Bson::Document), return a mutable reference to its value. Returns
906 /// [`None`] otherwise.
907 pub fn as_document_mut(&mut self) -> Option<&mut Document> {
908 match *self {
909 Bson::Document(ref mut v) => Some(v),
910 _ => None,
911 }
912 }
913
914 /// If `self` is [`Boolean`](Bson::Boolean), return its value. Returns [`None`] otherwise.
915 pub fn as_bool(&self) -> Option<bool> {
916 match *self {
917 Bson::Boolean(v) => Some(v),
918 _ => None,
919 }
920 }
921
922 /// If `self` is [`Int32`](Bson::Int32), return its value. Returns [`None`] otherwise.
923 pub fn as_i32(&self) -> Option<i32> {
924 match *self {
925 Bson::Int32(v) => Some(v),
926 _ => None,
927 }
928 }
929
930 /// If `self` is [`Int64`](Bson::Int64), return its value. Returns [`None`] otherwise.
931 pub fn as_i64(&self) -> Option<i64> {
932 match *self {
933 Bson::Int64(v) => Some(v),
934 _ => None,
935 }
936 }
937
938 /// If `self` is [`ObjectId`](Bson::ObjectId), return its value. Returns [`None`] otherwise.
939 pub fn as_object_id(&self) -> Option<oid::ObjectId> {
940 match *self {
941 Bson::ObjectId(v) => Some(v),
942 _ => None,
943 }
944 }
945
946 /// If `self` is [`ObjectId`](Bson::ObjectId), return a mutable reference to its value. Returns
947 /// [`None`] otherwise.
948 pub fn as_object_id_mut(&mut self) -> Option<&mut oid::ObjectId> {
949 match *self {
950 Bson::ObjectId(ref mut v) => Some(v),
951 _ => None,
952 }
953 }
954
955 /// If `self` is [`DateTime`](Bson::DateTime), return its value. Returns [`None`] otherwise.
956 pub fn as_datetime(&self) -> Option<&crate::DateTime> {
957 match *self {
958 Bson::DateTime(ref v) => Some(v),
959 _ => None,
960 }
961 }
962
963 /// If `self` is [`DateTime`](Bson::DateTime), return a mutable reference to its value. Returns
964 /// [`None`] otherwise.
965 pub fn as_datetime_mut(&mut self) -> Option<&mut crate::DateTime> {
966 match *self {
967 Bson::DateTime(ref mut v) => Some(v),
968 _ => None,
969 }
970 }
971
972 /// If `self` is [`Symbol`](Bson::Symbol), return its value. Returns [`None`] otherwise.
973 pub fn as_symbol(&self) -> Option<&str> {
974 match *self {
975 Bson::Symbol(ref v) => Some(v),
976 _ => None,
977 }
978 }
979
980 /// If `self` is [`Symbol`](Bson::Symbol), return a mutable reference to its value. Returns
981 /// [`None`] otherwise.
982 pub fn as_symbol_mut(&mut self) -> Option<&mut str> {
983 match *self {
984 Bson::Symbol(ref mut v) => Some(v),
985 _ => None,
986 }
987 }
988
989 /// If `self` is [`Timestamp`](Bson::Timestamp), return its value. Returns [`None`] otherwise.
990 pub fn as_timestamp(&self) -> Option<Timestamp> {
991 match *self {
992 Bson::Timestamp(timestamp) => Some(timestamp),
993 _ => None,
994 }
995 }
996
997 /// If `self` is [`Null`](Bson::Null), return `()`. Returns [`None`] otherwise.
998 pub fn as_null(&self) -> Option<()> {
999 match *self {
1000 Bson::Null => Some(()),
1001 _ => None,
1002 }
1003 }
1004
1005 /// If `self` is [`DbPointer`](Bson::DbPointer), return its value. Returns [`None`] otherwise.
1006 pub fn as_db_pointer(&self) -> Option<&DbPointer> {
1007 match self {
1008 Bson::DbPointer(ref db_pointer) => Some(db_pointer),
1009 _ => None,
1010 }
1011 }
1012 }
1013
1014 /// Represents a BSON timestamp value.
1015 #[derive(Debug, Eq, Ord, PartialEq, PartialOrd, Clone, Copy, Hash)]
1016 pub struct Timestamp {
1017 /// The number of seconds since the Unix epoch.
1018 pub time: u32,
1019
1020 /// An incrementing value to order timestamps with the same number of seconds in the `time`
1021 /// field.
1022 pub increment: u32,
1023 }
1024
1025 impl Display for Timestamp {
1026 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1027 write!(fmt, "Timestamp({}, {})", self.time, self.increment)
1028 }
1029 }
1030
1031 impl Timestamp {
1032 pub(crate) fn to_le_bytes(self) -> [u8; 8] {
1033 let mut out = [0; 8];
1034 out[0..4].copy_from_slice(&self.increment.to_le_bytes());
1035 out[4..8].copy_from_slice(&self.time.to_le_bytes());
1036 out
1037 }
1038
1039 pub(crate) fn from_le_bytes(bytes: [u8; 8]) -> Self {
1040 let mut inc_bytes = [0; 4];
1041 inc_bytes.copy_from_slice(&bytes[0..4]);
1042 let mut time_bytes = [0; 4];
1043 time_bytes.copy_from_slice(&bytes[4..8]);
1044 Self {
1045 increment: u32::from_le_bytes(inc_bytes),
1046 time: u32::from_le_bytes(time_bytes),
1047 }
1048 }
1049 }
1050
1051 /// Represents a BSON regular expression value.
1052 #[derive(Debug, Clone, PartialEq)]
1053 pub struct Regex {
1054 /// The regex pattern to match.
1055 pub pattern: String,
1056
1057 /// The options for the regex.
1058 ///
1059 /// Options are identified by characters, which must be stored in
1060 /// alphabetical order. Valid options are 'i' for case insensitive matching, 'm' for
1061 /// multiline matching, 'x' for verbose mode, 'l' to make \w, \W, etc. locale dependent,
1062 /// 's' for dotall mode ('.' matches everything), and 'u' to make \w, \W, etc. match
1063 /// unicode.
1064 pub options: String,
1065 }
1066
1067 impl Regex {
1068 pub(crate) fn new(pattern: impl AsRef<str>, options: impl AsRef<str>) -> Self {
1069 let mut chars: Vec<_> = options.as_ref().chars().collect();
1070 chars.sort_unstable();
1071 let options: String = chars.into_iter().collect();
1072 Self {
1073 pattern: pattern.as_ref().to_string(),
1074 options,
1075 }
1076 }
1077 }
1078
1079 impl Display for Regex {
1080 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1081 write!(fmt, "/{}/{}", self.pattern, self.options)
1082 }
1083 }
1084
1085 /// Represents a BSON code with scope value.
1086 #[derive(Debug, Clone, PartialEq)]
1087 pub struct JavaScriptCodeWithScope {
1088 /// The JavaScript code.
1089 pub code: String,
1090
1091 /// The scope document containing variable bindings.
1092 pub scope: Document,
1093 }
1094
1095 impl Display for JavaScriptCodeWithScope {
1096 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1097 fmt.write_str(&self.code)
1098 }
1099 }
1100
1101 /// Represents a DBPointer. (Deprecated)
1102 #[derive(Debug, Clone, PartialEq)]
1103 pub struct DbPointer {
1104 pub(crate) namespace: String,
1105 pub(crate) id: oid::ObjectId,
1106 }