1#[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#[derive(PartialEq, Clone)]
27#[non_exhaustive]
28pub enum ValueAccessError {
29 NotPresent,
31 UnexpectedType,
33}
34
35pub 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#[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
154pub struct IntoIter {
156 inner: indexmap::map::IntoIter<String, Bson>,
157}
158
159pub struct Iter<'a> {
161 inner: indexmap::map::Iter<'a, String, Bson>,
162}
163
164pub struct Keys<'a> {
166 inner: indexmap::map::Keys<'a, String, Bson>,
167}
168
169pub struct Values<'a> {
171 inner: indexmap::map::Values<'a, String, Bson>,
172}
173
174pub 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 pub fn new() -> Document {
254 Document {
255 inner: IndexMap::default(),
256 }
257 }
258
259 pub fn iter(&self) -> Iter {
261 self.into_iter()
262 }
263
264 pub fn iter_mut(&mut self) -> IterMut {
266 IterMut {
267 inner: self.inner.iter_mut(),
268 }
269 }
270
271 pub fn clear(&mut self) {
273 self.inner.clear();
274 }
275
276 pub fn get(&self, key: impl AsRef<str>) -> Option<&Bson> {
278 self.inner.get(key.as_ref())
279 }
280
281 pub fn get_mut(&mut self, key: impl AsRef<str>) -> Option<&mut Bson> {
283 self.inner.get_mut(key.as_ref())
284 }
285
286 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 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 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 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 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 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 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 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 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 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 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 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 pub fn is_null(&self, key: impl AsRef<str>) -> bool {
405 self.get(key) == Some(&Bson::Null)
406 }
407
408 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 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 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 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 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 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 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 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 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 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 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 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 pub fn contains_key(&self, key: impl AsRef<str>) -> bool {
535 self.inner.contains_key(key.as_ref())
536 }
537
538 pub fn keys(&self) -> Keys {
540 Keys {
541 inner: self.inner.keys(),
542 }
543 }
544
545 pub fn values(&self) -> Values {
547 Values {
548 inner: self.inner.values(),
549 }
550 }
551
552 pub fn len(&self) -> usize {
554 self.inner.len()
555 }
556
557 pub fn is_empty(&self) -> bool {
559 self.inner.is_empty()
560 }
561
562 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 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 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 pub fn from_reader<R: Read>(mut reader: R) -> crate::de::Result<Document> {
638 Self::decode(&mut reader, false)
639 }
640
641 #[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
653pub enum Entry<'a> {
657 Occupied(OccupiedEntry<'a>),
659
660 Vacant(VacantEntry<'a>),
662}
663
664impl<'a> Entry<'a> {
665 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 pub fn or_insert(self, default: Bson) -> &'a mut Bson {
683 self.into_indexmap_entry().or_insert(default)
684 }
685
686 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
694pub struct VacantEntry<'a> {
696 inner: indexmap::map::VacantEntry<'a, String, Bson>,
697}
698
699impl VacantEntry<'_> {
700 fn key(&self) -> &str {
703 self.inner.key()
704 }
705}
706
707pub struct OccupiedEntry<'a> {
709 inner: indexmap::map::OccupiedEntry<'a, String, Bson>,
710}
711
712impl OccupiedEntry<'_> {
713 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}