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