bson/
document.rs

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