bson/
document.rs

1//! A BSON document represented as an associative HashMap with insertion ordering.
2
3use std::{
4    fmt::{self, Debug, Display, Formatter},
5    hash::Hash,
6    io::{Read, Write},
7    iter::{Extend, FromIterator, IntoIterator},
8    ops::Index,
9};
10
11use ahash::RandomState;
12use indexmap::IndexMap;
13
14use crate::{
15    bson::{Array, Bson, Timestamp},
16    error::{Error, Result},
17    oid::ObjectId,
18    spec::{BinarySubtype, ElementType},
19    Binary,
20    Decimal128,
21};
22
23/// A BSON document represented as an associative HashMap with insertion ordering.
24#[derive(Clone, PartialEq, Eq)]
25pub struct Document {
26    inner: IndexMap<String, Bson, RandomState>,
27}
28
29impl Default for Document {
30    fn default() -> Self {
31        Document::new()
32    }
33}
34
35impl Hash for Document {
36    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
37        let mut entries = Vec::from_iter(&self.inner);
38        entries.sort_unstable_by(|a, b| a.0.cmp(b.0));
39        entries.hash(state);
40    }
41}
42
43impl Display for Document {
44    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
45        let indent = fmt.width().unwrap_or(2);
46        let indent_str = " ".repeat(indent);
47
48        write!(fmt, "{{")?;
49        if fmt.alternate() && !self.inner.is_empty() {
50            fmt.write_str("\n")?;
51        }
52
53        let mut first = true;
54        for (k, v) in self {
55            if !fmt.alternate() {
56                if first {
57                    first = false;
58                    write!(fmt, " ")?;
59                } else {
60                    fmt.write_str(", ")?;
61                }
62                write!(fmt, "\"{}\": {}", k, v)?;
63            }
64
65            if fmt.alternate() {
66                if first {
67                    first = false;
68                } else {
69                    fmt.write_str(",\n")?;
70                }
71                match v {
72                    Bson::Document(ref doc) => {
73                        let new_indent = indent + 2;
74                        write!(fmt, "{indent_str}\"{}\": {doc:#new_indent$}", k)?;
75                    }
76                    Bson::Array(_arr) => {
77                        let new_indent = indent + 2;
78                        write!(fmt, "{indent_str}\"{}\": {v:#new_indent$}", k)?;
79                    }
80                    _ => {
81                        write!(fmt, "{indent_str}\"{}\": {}", k, v)?;
82                    }
83                }
84            }
85        }
86
87        let closing_bracket_indent_str = " ".repeat(indent - 2);
88        if fmt.alternate() && !self.inner.is_empty() {
89            write!(fmt, "\n{closing_bracket_indent_str}}}")
90        } else {
91            write!(fmt, "{}}}", if !first { " " } else { "" })
92        }
93    }
94}
95
96impl Debug for Document {
97    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
98        write!(fmt, "Document(")?;
99        Debug::fmt(&self.inner, fmt)?;
100        write!(fmt, ")")
101    }
102}
103
104impl Index<&str> for Document {
105    type Output = Bson;
106
107    fn index(&self, index: &str) -> &Self::Output {
108        match self.get(index) {
109            Some(v) => v,
110            None => &Bson::Null,
111        }
112    }
113}
114
115/// An iterator over Document entries.
116pub struct IntoIter {
117    inner: indexmap::map::IntoIter<String, Bson>,
118}
119
120/// An owning iterator over Document entries.
121pub struct Iter<'a> {
122    inner: indexmap::map::Iter<'a, String, Bson>,
123}
124
125/// An iterator over an Document's keys.
126pub struct Keys<'a> {
127    inner: indexmap::map::Keys<'a, String, Bson>,
128}
129
130/// An iterator over an Document's values.
131pub struct Values<'a> {
132    inner: indexmap::map::Values<'a, String, Bson>,
133}
134
135/// An iterator over a [`Document`]'s keys and mutable values.
136pub struct IterMut<'a> {
137    inner: indexmap::map::IterMut<'a, String, Bson>,
138}
139
140impl<'a> Iterator for Keys<'a> {
141    type Item = &'a String;
142
143    fn next(&mut self) -> Option<&'a String> {
144        self.inner.next()
145    }
146}
147
148impl<'a> Iterator for Values<'a> {
149    type Item = &'a Bson;
150
151    fn next(&mut self) -> Option<&'a Bson> {
152        self.inner.next()
153    }
154}
155
156impl IntoIterator for Document {
157    type Item = (String, Bson);
158    type IntoIter = IntoIter;
159
160    fn into_iter(self) -> Self::IntoIter {
161        IntoIter {
162            inner: self.inner.into_iter(),
163        }
164    }
165}
166
167impl<'a> IntoIterator for &'a Document {
168    type Item = (&'a String, &'a Bson);
169    type IntoIter = Iter<'a>;
170
171    fn into_iter(self) -> Self::IntoIter {
172        Iter {
173            inner: self.inner.iter(),
174        }
175    }
176}
177
178impl FromIterator<(String, Bson)> for Document {
179    fn from_iter<T: IntoIterator<Item = (String, Bson)>>(iter: T) -> Self {
180        let mut doc = Document::new();
181        for (k, v) in iter {
182            doc.insert(k, v);
183        }
184        doc
185    }
186}
187
188impl Iterator for IntoIter {
189    type Item = (String, Bson);
190
191    fn next(&mut self) -> Option<(String, Bson)> {
192        self.inner.next()
193    }
194}
195
196impl<'a> Iterator for Iter<'a> {
197    type Item = (&'a String, &'a Bson);
198
199    fn next(&mut self) -> Option<(&'a String, &'a Bson)> {
200        self.inner.next()
201    }
202}
203
204impl<'a> Iterator for IterMut<'a> {
205    type Item = (&'a String, &'a mut Bson);
206
207    fn next(&mut self) -> Option<(&'a String, &'a mut Bson)> {
208        self.inner.next()
209    }
210}
211
212impl Document {
213    /// Returns a new empty document.
214    pub fn new() -> Document {
215        Document {
216            inner: IndexMap::default(),
217        }
218    }
219
220    /// Returns an iterator over the contents of the document.
221    pub fn iter(&self) -> Iter<'_> {
222        self.into_iter()
223    }
224
225    /// Returns an iterator over mutable references to the contents of the document.
226    pub fn iter_mut(&mut self) -> IterMut<'_> {
227        IterMut {
228            inner: self.inner.iter_mut(),
229        }
230    }
231
232    /// Removes all values from the document.
233    pub fn clear(&mut self) {
234        self.inner.clear();
235    }
236
237    /// Returns a reference to the [`Bson`] value that corresponds to the given key, if present.
238    pub fn get(&self, key: impl AsRef<str>) -> Option<&Bson> {
239        self.inner.get(key.as_ref())
240    }
241
242    /// Returns a mutable reference to the [`Bson`] value that corresponds to the given key, if
243    /// present.
244    pub fn get_mut(&mut self, key: impl AsRef<str>) -> Option<&mut Bson> {
245        self.inner.get_mut(key.as_ref())
246    }
247
248    /// Returns the value for the given key if one is present and is of type
249    /// [`ElementType::Double`].
250    pub fn get_f64(&self, key: impl AsRef<str>) -> Result<f64> {
251        let key = key.as_ref();
252        match self.get(key) {
253            Some(&Bson::Double(v)) => Ok(v),
254            Some(bson) => Err(Error::value_access_unexpected_type(
255                bson.element_type(),
256                ElementType::Double,
257            )),
258            None => Err(Error::value_access_not_present()),
259        }
260        .map_err(|e| e.with_key(key))
261    }
262
263    /// Returns a mutable reference to the value for the given key if one is present and is of type
264    /// [`ElementType::Double`].
265    pub fn get_f64_mut(&mut self, key: impl AsRef<str>) -> Result<&mut f64> {
266        let key = key.as_ref();
267        match self.get_mut(key) {
268            Some(&mut Bson::Double(ref mut v)) => Ok(v),
269            Some(bson) => Err(Error::value_access_unexpected_type(
270                bson.element_type(),
271                ElementType::Double,
272            )),
273            None => Err(Error::value_access_not_present()),
274        }
275        .map_err(|e| e.with_key(key))
276    }
277
278    /// Returns a reference to the value for the given key if one is present and is of type
279    /// [`ElementType::Decimal128`].
280    pub fn get_decimal128(&self, key: impl AsRef<str>) -> Result<&Decimal128> {
281        let key = key.as_ref();
282        match self.get(key) {
283            Some(Bson::Decimal128(v)) => Ok(v),
284            Some(bson) => Err(Error::value_access_unexpected_type(
285                bson.element_type(),
286                ElementType::Decimal128,
287            )),
288            None => Err(Error::value_access_not_present()),
289        }
290        .map_err(|e| e.with_key(key))
291    }
292
293    /// Returns a mutable reference to the value for the given key if one is present and is of type
294    /// [`ElementType::Decimal128`].
295    pub fn get_decimal128_mut(&mut self, key: impl AsRef<str>) -> Result<&mut Decimal128> {
296        let key = key.as_ref();
297        match self.get_mut(key) {
298            Some(&mut Bson::Decimal128(ref mut v)) => Ok(v),
299            Some(bson) => Err(Error::value_access_unexpected_type(
300                bson.element_type(),
301                ElementType::Decimal128,
302            )),
303            None => Err(Error::value_access_not_present()),
304        }
305        .map_err(|e| e.with_key(key))
306    }
307
308    /// Returns a reference to the value for the given key if one is present and is of type
309    /// [`ElementType::String`].
310    pub fn get_str(&self, key: impl AsRef<str>) -> Result<&str> {
311        let key = key.as_ref();
312        match self.get(key) {
313            Some(Bson::String(v)) => Ok(v.as_str()),
314            Some(bson) => Err(Error::value_access_unexpected_type(
315                bson.element_type(),
316                ElementType::String,
317            )),
318            None => Err(Error::value_access_not_present()),
319        }
320        .map_err(|e| e.with_key(key))
321    }
322
323    /// Returns a mutable reference to the value for the given key if one is present and is of type
324    /// [`ElementType::String`].
325    pub fn get_str_mut(&mut self, key: impl AsRef<str>) -> Result<&mut str> {
326        let key = key.as_ref();
327        match self.get_mut(key) {
328            Some(&mut Bson::String(ref mut v)) => Ok(v.as_mut_str()),
329            Some(bson) => Err(Error::value_access_unexpected_type(
330                bson.element_type(),
331                ElementType::String,
332            )),
333            None => Err(Error::value_access_not_present()),
334        }
335        .map_err(|e| e.with_key(key))
336    }
337
338    /// Returns a reference to the value for the given key if one is present and is of type
339    /// [`ElementType::Array`].
340    pub fn get_array(&self, key: impl AsRef<str>) -> Result<&Array> {
341        let key = key.as_ref();
342        match self.get(key) {
343            Some(Bson::Array(v)) => Ok(v),
344            Some(bson) => Err(Error::value_access_unexpected_type(
345                bson.element_type(),
346                ElementType::Array,
347            )),
348            None => Err(Error::value_access_not_present()),
349        }
350        .map_err(|e| e.with_key(key))
351    }
352
353    /// Returns a mutable reference to the value for the given key if one is present and is of type
354    /// [`ElementType::Array`].
355    pub fn get_array_mut(&mut self, key: impl AsRef<str>) -> Result<&mut Array> {
356        let key = key.as_ref();
357        match self.get_mut(key) {
358            Some(&mut Bson::Array(ref mut v)) => Ok(v),
359            Some(bson) => Err(Error::value_access_unexpected_type(
360                bson.element_type(),
361                ElementType::Array,
362            )),
363            None => Err(Error::value_access_not_present()),
364        }
365        .map_err(|e| e.with_key(key))
366    }
367
368    /// Returns a reference to the value for the given key if one is present and is of type
369    /// [`ElementType::EmbeddedDocument`].
370    pub fn get_document(&self, key: impl AsRef<str>) -> Result<&Document> {
371        let key = key.as_ref();
372        match self.get(key) {
373            Some(Bson::Document(v)) => Ok(v),
374            Some(bson) => Err(Error::value_access_unexpected_type(
375                bson.element_type(),
376                ElementType::EmbeddedDocument,
377            )),
378            None => Err(Error::value_access_not_present()),
379        }
380        .map_err(|e| e.with_key(key))
381    }
382
383    /// Returns a mutable reference to the value for the given key if one is present and is of type
384    /// [`ElementType::EmbeddedDocument`].
385    pub fn get_document_mut(&mut self, key: impl AsRef<str>) -> Result<&mut Document> {
386        let key = key.as_ref();
387        match self.get_mut(key) {
388            Some(&mut Bson::Document(ref mut v)) => Ok(v),
389            Some(bson) => Err(Error::value_access_unexpected_type(
390                bson.element_type(),
391                ElementType::EmbeddedDocument,
392            )),
393            None => Err(Error::value_access_not_present()),
394        }
395        .map_err(|e| e.with_key(key))
396    }
397
398    /// Returns a reference to the value for the given key if one is present and is of type
399    /// [`ElementType::Boolean`].
400    pub fn get_bool(&self, key: impl AsRef<str>) -> Result<bool> {
401        let key = key.as_ref();
402        match self.get(key) {
403            Some(&Bson::Boolean(v)) => Ok(v),
404            Some(bson) => Err(Error::value_access_unexpected_type(
405                bson.element_type(),
406                ElementType::Boolean,
407            )),
408            None => Err(Error::value_access_not_present()),
409        }
410        .map_err(|e| e.with_key(key))
411    }
412
413    /// Returns a mutable reference to the value for the given key if one is present and is of type
414    /// [`ElementType::Boolean`].
415    pub fn get_bool_mut(&mut self, key: impl AsRef<str>) -> Result<&mut bool> {
416        let key = key.as_ref();
417        match self.get_mut(key) {
418            Some(&mut Bson::Boolean(ref mut v)) => Ok(v),
419            Some(bson) => Err(Error::value_access_unexpected_type(
420                bson.element_type(),
421                ElementType::Boolean,
422            )),
423            None => Err(Error::value_access_not_present()),
424        }
425        .map_err(|e| e.with_key(key))
426    }
427
428    /// Returns [`Bson::Null`] if the given key corresponds to a [`Bson::Null`] value.
429    pub fn get_null(&self, key: impl AsRef<str>) -> Result<Bson> {
430        let key = key.as_ref();
431        match self.get(key) {
432            Some(&Bson::Null) => Ok(Bson::Null),
433            Some(bson) => Err(Error::value_access_unexpected_type(
434                bson.element_type(),
435                ElementType::Null,
436            )),
437            None => Err(Error::value_access_not_present()),
438        }
439        .map_err(|e| e.with_key(key))
440    }
441
442    /// Returns the value for the given key if one is present and is of type [`ElementType::Int32`].
443    pub fn get_i32(&self, key: impl AsRef<str>) -> Result<i32> {
444        let key = key.as_ref();
445        match self.get(key) {
446            Some(&Bson::Int32(v)) => Ok(v),
447            Some(bson) => Err(Error::value_access_unexpected_type(
448                bson.element_type(),
449                ElementType::Int32,
450            )),
451            None => Err(Error::value_access_not_present()),
452        }
453        .map_err(|e| e.with_key(key))
454    }
455
456    /// Returns a mutable reference to the value for the given key if one is present and is of type
457    /// [`ElementType::Int32`].
458    pub fn get_i32_mut(&mut self, key: impl AsRef<str>) -> Result<&mut i32> {
459        let key = key.as_ref();
460        match self.get_mut(key) {
461            Some(&mut Bson::Int32(ref mut v)) => Ok(v),
462            Some(bson) => Err(Error::value_access_unexpected_type(
463                bson.element_type(),
464                ElementType::Int32,
465            )),
466            None => Err(Error::value_access_not_present()),
467        }
468        .map_err(|e| e.with_key(key))
469    }
470
471    /// Returns the value for the given key if one is present and is of type [`ElementType::Int64`].
472    pub fn get_i64(&self, key: impl AsRef<str>) -> Result<i64> {
473        let key = key.as_ref();
474        match self.get(key) {
475            Some(&Bson::Int64(v)) => Ok(v),
476            Some(bson) => Err(Error::value_access_unexpected_type(
477                bson.element_type(),
478                ElementType::Int64,
479            )),
480            None => Err(Error::value_access_not_present()),
481        }
482        .map_err(|e| e.with_key(key))
483    }
484
485    /// Returns a mutable reference to the value for the given key if one is present and is of type
486    /// [`ElementType::Int64`].
487    pub fn get_i64_mut(&mut self, key: impl AsRef<str>) -> Result<&mut i64> {
488        let key = key.as_ref();
489        match self.get_mut(key) {
490            Some(&mut Bson::Int64(ref mut v)) => Ok(v),
491            Some(bson) => Err(Error::value_access_unexpected_type(
492                bson.element_type(),
493                ElementType::Int64,
494            )),
495            None => Err(Error::value_access_not_present()),
496        }
497        .map_err(|e| e.with_key(key))
498    }
499
500    /// Returns the value for the given key if one is present and is of type
501    /// [`ElementType::Timestamp`].
502    pub fn get_timestamp(&self, key: impl AsRef<str>) -> Result<Timestamp> {
503        let key = key.as_ref();
504        match self.get(key) {
505            Some(&Bson::Timestamp(timestamp)) => Ok(timestamp),
506            Some(bson) => Err(Error::value_access_unexpected_type(
507                bson.element_type(),
508                ElementType::Timestamp,
509            )),
510            None => Err(Error::value_access_not_present()),
511        }
512        .map_err(|e| e.with_key(key))
513    }
514
515    /// Returns a mutable reference to the value for the given key if one is present and is of type
516    /// [`ElementType::Timestamp`].
517    pub fn get_timestamp_mut(&mut self, key: impl AsRef<str>) -> Result<&mut Timestamp> {
518        let key = key.as_ref();
519        match self.get_mut(key) {
520            Some(&mut Bson::Timestamp(ref mut timestamp)) => Ok(timestamp),
521            Some(bson) => Err(Error::value_access_unexpected_type(
522                bson.element_type(),
523                ElementType::Timestamp,
524            )),
525            None => Err(Error::value_access_not_present()),
526        }
527        .map_err(|e| e.with_key(key))
528    }
529
530    /// Returns a reference to the value for the given key if one is present and is of type
531    /// [`ElementType::Binary`] with binary subtype [`BinarySubtype::Generic`].
532    pub fn get_binary_generic(&self, key: impl AsRef<str>) -> Result<&Vec<u8>> {
533        let key = key.as_ref();
534        match self.get(key) {
535            Some(&Bson::Binary(Binary {
536                subtype: BinarySubtype::Generic,
537                ref bytes,
538            })) => Ok(bytes),
539            Some(bson) => Err(Error::value_access_unexpected_type(
540                bson.element_type(),
541                ElementType::Binary,
542            )),
543            None => Err(Error::value_access_not_present()),
544        }
545        .map_err(|e| e.with_key(key))
546    }
547
548    /// Returns a mutable reference to the value for the given key if one is present and is of type
549    /// [`ElementType::Binary`] with binary subtype [`BinarySubtype::Generic`].
550    pub fn get_binary_generic_mut(&mut self, key: impl AsRef<str>) -> Result<&mut Vec<u8>> {
551        let key = key.as_ref();
552        match self.get_mut(key) {
553            Some(&mut Bson::Binary(Binary {
554                subtype: BinarySubtype::Generic,
555                ref mut bytes,
556            })) => Ok(bytes),
557            Some(bson) => Err(Error::value_access_unexpected_type(
558                bson.element_type(),
559                ElementType::Binary,
560            )),
561            None => Err(Error::value_access_not_present()),
562        }
563        .map_err(|e| e.with_key(key))
564    }
565
566    /// Returns the value for the given key if one is present and is of type
567    /// [`ElementType::ObjectId`].
568    pub fn get_object_id(&self, key: impl AsRef<str>) -> Result<ObjectId> {
569        let key = key.as_ref();
570        match self.get(key) {
571            Some(&Bson::ObjectId(v)) => Ok(v),
572            Some(bson) => Err(Error::value_access_unexpected_type(
573                bson.element_type(),
574                ElementType::ObjectId,
575            )),
576            None => Err(Error::value_access_not_present()),
577        }
578        .map_err(|e| e.with_key(key))
579    }
580
581    /// Returns a mutable reference to the value for the given key if one is present and is of type
582    /// [`ElementType::ObjectId`].
583    pub fn get_object_id_mut(&mut self, key: impl AsRef<str>) -> Result<&mut ObjectId> {
584        let key = key.as_ref();
585        match self.get_mut(key) {
586            Some(&mut Bson::ObjectId(ref mut v)) => Ok(v),
587            Some(bson) => Err(Error::value_access_unexpected_type(
588                bson.element_type(),
589                ElementType::ObjectId,
590            )),
591            None => Err(Error::value_access_not_present()),
592        }
593        .map_err(|e| e.with_key(key))
594    }
595
596    /// Returns a reference to the value for the given key if one is present and is of type
597    /// [`ElementType::DateTime`].
598    pub fn get_datetime(&self, key: impl AsRef<str>) -> Result<&crate::DateTime> {
599        let key = key.as_ref();
600        match self.get(key) {
601            Some(Bson::DateTime(v)) => Ok(v),
602            Some(bson) => Err(Error::value_access_unexpected_type(
603                bson.element_type(),
604                ElementType::DateTime,
605            )),
606            None => Err(Error::value_access_not_present()),
607        }
608        .map_err(|e| e.with_key(key))
609    }
610
611    /// Returns a mutable reference to the value for the given key if one is present and is of type
612    /// [`ElementType::DateTime`].
613    pub fn get_datetime_mut(&mut self, key: impl AsRef<str>) -> Result<&mut crate::DateTime> {
614        let key = key.as_ref();
615        match self.get_mut(key) {
616            Some(&mut Bson::DateTime(ref mut v)) => Ok(v),
617            Some(bson) => Err(Error::value_access_unexpected_type(
618                bson.element_type(),
619                ElementType::DateTime,
620            )),
621            None => Err(Error::value_access_not_present()),
622        }
623        .map_err(|e| e.with_key(key))
624    }
625
626    /// Returns whether the map contains a value for the specified key.
627    pub fn contains_key(&self, key: impl AsRef<str>) -> bool {
628        self.inner.contains_key(key.as_ref())
629    }
630
631    /// Returns an iterator over the keys in the document.
632    pub fn keys(&self) -> Keys<'_> {
633        Keys {
634            inner: self.inner.keys(),
635        }
636    }
637
638    /// Returns an iterator over the values in the document.
639    pub fn values(&self) -> Values<'_> {
640        Values {
641            inner: self.inner.values(),
642        }
643    }
644
645    /// Returns the number of elements in the document.
646    pub fn len(&self) -> usize {
647        self.inner.len()
648    }
649
650    /// Returns whether the document is empty.
651    pub fn is_empty(&self) -> bool {
652        self.inner.is_empty()
653    }
654
655    /// Inserts the provided key-value pair into the document. Any type that implements `Into<Bson>`
656    /// can be specified as a value. If a value is already present for the given key, it will be
657    /// overridden and returned.
658    pub fn insert<KT: Into<String>, BT: Into<Bson>>(&mut self, key: KT, val: BT) -> Option<Bson> {
659        self.inner.insert(key.into(), val.into())
660    }
661
662    /// Removes and returns the value that corresponds to the given key if present. Computes in
663    /// **O(n)** time (average).
664    pub fn remove(&mut self, key: impl AsRef<str>) -> Option<Bson> {
665        self.inner.shift_remove(key.as_ref())
666    }
667
668    /// Returns an [`Entry`] for the given key.
669    pub fn entry(&mut self, k: impl Into<String>) -> Entry<'_> {
670        match self.inner.entry(k.into()) {
671            indexmap::map::Entry::Occupied(o) => Entry::Occupied(OccupiedEntry { inner: o }),
672            indexmap::map::Entry::Vacant(v) => Entry::Vacant(VacantEntry { inner: v }),
673        }
674    }
675
676    /// Attempt to encode the [`Document`] into a byte [`Vec`].
677    pub fn to_vec(&self) -> Result<Vec<u8>> {
678        Ok(crate::RawDocumentBuf::try_from(self)?.into_bytes())
679    }
680
681    /// Attempts to encode the [`Document`] into a byte stream.
682    ///
683    /// While the method signature indicates an owned writer must be passed in, a mutable reference
684    /// may also be passed in due to blanket implementations of [`Write`] provided in the standard
685    /// library.
686    ///
687    /// ```
688    /// # fn main() -> bson::error::Result<()> {
689    /// use bson::doc;
690    ///
691    /// let mut v: Vec<u8> = Vec::new();
692    /// let doc = doc! { "x" : 1 };
693    /// doc.to_writer(&mut v)?;
694    /// # Ok(())
695    /// # }
696    /// ```
697    pub fn to_writer<W: Write>(&self, mut writer: W) -> crate::error::Result<()> {
698        let buf = crate::RawDocumentBuf::try_from(self)?;
699        writer.write_all(buf.as_bytes())?;
700        Ok(())
701    }
702
703    /// Attempts to decode a [`Document`] from a byte stream.
704    ///
705    /// While the method signature indicates an owned reader must be passed in, a mutable reference
706    /// may also be passed in due to blanket implementations of [`Read`] provided in the standard
707    /// library.
708    ///
709    /// ```
710    /// # use std::error::Error;
711    /// # fn main() -> std::result::Result<(), Box<dyn Error>> {
712    /// use bson::{doc, Document};
713    /// use std::io::Cursor;
714    ///
715    /// let mut v: Vec<u8> = Vec::new();
716    /// let doc = doc! { "x" : 1 };
717    /// doc.to_writer(&mut v)?;
718    ///
719    /// // read from mutable reference
720    /// let mut reader = Cursor::new(v.clone());
721    /// let doc1 = Document::from_reader(&mut reader)?;
722    ///
723    /// // read from owned value
724    /// let doc2 = Document::from_reader(Cursor::new(v))?;
725    ///
726    /// assert_eq!(doc, doc1);
727    /// assert_eq!(doc, doc2);
728    /// # Ok(())
729    /// # }
730    /// ```
731    pub fn from_reader<R: Read>(reader: R) -> crate::error::Result<Document> {
732        let raw = crate::raw::RawDocumentBuf::from_reader(reader)?;
733        raw.try_into()
734    }
735
736    pub(crate) fn append_to(&self, buf: &mut Vec<u8>) -> crate::error::Result<()> {
737        let mut writer = crate::raw::doc_writer::DocWriter::open(buf);
738        for (k, v) in self {
739            writer.append_key(v.element_type(), k.as_str().try_into()?);
740            v.append_to(writer.buffer())?;
741        }
742        Ok(())
743    }
744}
745
746/// A view into a single entry in a document, which may either be vacant or occupied.
747pub enum Entry<'a> {
748    /// An occupied entry.
749    Occupied(OccupiedEntry<'a>),
750
751    /// A vacant entry.
752    Vacant(VacantEntry<'a>),
753}
754
755impl<'a> Entry<'a> {
756    /// Returns a reference to this entry's key.
757    pub fn key(&self) -> &str {
758        match self {
759            Self::Vacant(v) => v.key(),
760            Self::Occupied(o) => o.key(),
761        }
762    }
763
764    fn into_indexmap_entry(self) -> indexmap::map::Entry<'a, String, Bson> {
765        match self {
766            Self::Occupied(o) => indexmap::map::Entry::Occupied(o.inner),
767            Self::Vacant(v) => indexmap::map::Entry::Vacant(v.inner),
768        }
769    }
770
771    /// Inserts the given default value in the entry if it is vacant and returns a mutable reference
772    /// to it. Otherwise a mutable reference to an already existent value is returned.
773    pub fn or_insert(self, default: Bson) -> &'a mut Bson {
774        self.into_indexmap_entry().or_insert(default)
775    }
776
777    /// Inserts the result of the `default` function in the entry if it is vacant and returns a
778    /// mutable reference to it. Otherwise a mutable reference to an already existent value is
779    /// returned.
780    pub fn or_insert_with<F: FnOnce() -> Bson>(self, default: F) -> &'a mut Bson {
781        self.into_indexmap_entry().or_insert_with(default)
782    }
783}
784
785/// A view into a vacant entry in a [Document]. It is part of the [Entry] enum.
786pub struct VacantEntry<'a> {
787    inner: indexmap::map::VacantEntry<'a, String, Bson>,
788}
789
790impl VacantEntry<'_> {
791    /// Gets a reference to the key that would be used when inserting a value through the
792    /// [VacantEntry].
793    fn key(&self) -> &str {
794        self.inner.key()
795    }
796}
797
798/// A view into an occupied entry in a [Document]. It is part of the [Entry] enum.
799pub struct OccupiedEntry<'a> {
800    inner: indexmap::map::OccupiedEntry<'a, String, Bson>,
801}
802
803impl OccupiedEntry<'_> {
804    /// Gets a reference to the key in the entry.
805    pub fn key(&self) -> &str {
806        self.inner.key()
807    }
808}
809
810impl Extend<(String, Bson)> for Document {
811    fn extend<T: IntoIterator<Item = (String, Bson)>>(&mut self, iter: T) {
812        for (k, v) in iter {
813            self.insert(k, v);
814        }
815    }
816}