| 1 |
use std::{ |
| 2 |
borrow::{Borrow, Cow}, |
| 3 |
convert::{TryFrom, TryInto}, |
| 4 |
iter::FromIterator, |
| 5 |
ops::Deref, |
| 6 |
}; |
| 7 |
|
| 8 |
use serde::{Deserialize, Serialize}; |
| 9 |
|
| 10 |
use crate::{de::MIN_BSON_DOCUMENT_SIZE, spec::BinarySubtype, Document}; |
| 11 |
|
| 12 |
use super::{ |
| 13 |
bson::RawBson, |
| 14 |
iter::Iter, |
| 15 |
serde::OwnedOrBorrowedRawDocument, |
| 16 |
Error, |
| 17 |
ErrorKind, |
| 18 |
RawBsonRef, |
| 19 |
RawDocument, |
| 20 |
RawIter, |
| 21 |
Result, |
| 22 |
}; |
| 23 |
|
| 24 |
/// An owned BSON document (akin to [`std::path::PathBuf`]), backed by a buffer of raw BSON bytes. |
| 25 |
/// This can be created from a `Vec<u8>` or a [`crate::Document`]. |
| 26 |
/// |
| 27 |
/// Accessing elements within a [`RawDocumentBuf`] is similar to element access in |
| 28 |
/// [`crate::Document`], but because the contents are parsed during iteration instead of at creation |
| 29 |
/// time, format errors can happen at any time during use. |
| 30 |
/// |
| 31 |
/// Iterating over a [`RawDocumentBuf`] yields either an error or a key-value pair that borrows from |
| 32 |
/// the original document without making any additional allocations. |
| 33 |
/// |
| 34 |
/// ``` |
| 35 |
/// # use bson::raw::Error; |
| 36 |
/// use bson::raw::RawDocumentBuf; |
| 37 |
/// |
| 38 |
/// let doc = RawDocumentBuf::from_bytes(b"\x13\x00\x00\x00\x02hi\x00\x06\x00\x00\x00y'all\x00\x00".to_vec())?; |
| 39 |
/// let mut iter = doc.iter(); |
| 40 |
/// let (key, value) = iter.next().unwrap()?; |
| 41 |
/// assert_eq!(key, "hi"); |
| 42 |
/// assert_eq!(value.as_str(), Some("y'all")); |
| 43 |
/// assert!(iter.next().is_none()); |
| 44 |
/// # Ok::<(), Error>(()) |
| 45 |
/// ``` |
| 46 |
/// |
| 47 |
/// This type implements [`Deref`] to [`RawDocument`], meaning that all methods on [`RawDocument`] |
| 48 |
/// are available on [`RawDocumentBuf`] values as well. This includes [`RawDocument::get`] or any of |
| 49 |
/// the type-specific getters, such as [`RawDocument::get_object_id`] or [`RawDocument::get_str`]. |
| 50 |
/// Note that accessing elements is an O(N) operation, as it requires iterating through the document |
| 51 |
/// from the beginning to find the requested key. |
| 52 |
/// |
| 53 |
/// ``` |
| 54 |
/// use bson::raw::RawDocumentBuf; |
| 55 |
/// |
| 56 |
/// let doc = RawDocumentBuf::from_bytes(b"\x13\x00\x00\x00\x02hi\x00\x06\x00\x00\x00y'all\x00\x00".to_vec())?; |
| 57 |
/// assert_eq!(doc.get_str("hi")?, "y'all"); |
| 58 |
/// # Ok::<(), Box<dyn std::error::Error>>(()) |
| 59 |
/// ``` |
| 60 |
#[derive(Clone, PartialEq)] |
| 61 |
pub struct RawDocumentBuf { |
| 62 |
data: Vec<u8>, |
| 63 |
} |
| 64 |
|
| 65 |
impl RawDocumentBuf { |
| 66 |
/// Creates a new, empty [`RawDocumentBuf`]. |
| 67 |
pub fn new() -> RawDocumentBuf { |
| 68 |
let mut data = Vec::new(); |
| 69 |
data.extend(MIN_BSON_DOCUMENT_SIZE.to_le_bytes()); |
| 70 |
data.push(0); |
| 71 |
Self { data } |
| 72 |
} |
| 73 |
|
| 74 |
/// Constructs a new [`RawDocumentBuf`], validating _only_ the |
| 75 |
/// following invariants: |
| 76 |
/// * `data` is at least five bytes long (the minimum for a valid BSON document) |
| 77 |
/// * the initial four bytes of `data` accurately represent the length of the bytes as |
| 78 |
/// required by the BSON spec. |
| 79 |
/// * the last byte of `data` is a 0 |
| 80 |
/// |
| 81 |
/// Note that the internal structure of the bytes representing the |
| 82 |
/// BSON elements is _not_ validated at all by this method. If the |
| 83 |
/// bytes do not conform to the BSON spec, then method calls on |
| 84 |
/// the RawDocument will return Errors where appropriate. |
| 85 |
/// |
| 86 |
/// ``` |
| 87 |
/// # use bson::raw::{RawDocumentBuf, Error}; |
| 88 |
/// let doc = RawDocumentBuf::from_bytes(b"\x05\0\0\0\0".to_vec())?; |
| 89 |
/// # Ok::<(), Error>(()) |
| 90 |
/// ``` |
| 91 |
pub fn from_bytes(data: Vec<u8>) -> Result<RawDocumentBuf> { |
| 92 |
let _ = RawDocument::from_bytes(data.as_slice())?; |
| 93 |
Ok(Self { data }) |
| 94 |
} |
| 95 |
|
| 96 |
/// Create a [`RawDocumentBuf`] from a [`Document`]. |
| 97 |
/// |
| 98 |
/// ``` |
| 99 |
/// # use bson::raw::Error; |
| 100 |
/// use bson::{doc, oid::ObjectId, raw::RawDocumentBuf}; |
| 101 |
/// |
| 102 |
/// let document = doc! { |
| 103 |
/// "_id": ObjectId::new(), |
| 104 |
/// "name": "Herman Melville", |
| 105 |
/// "title": "Moby-Dick", |
| 106 |
/// }; |
| 107 |
/// let doc = RawDocumentBuf::from_document(&document)?; |
| 108 |
/// # Ok::<(), Error>(()) |
| 109 |
/// ``` |
| 110 |
pub fn from_document(doc: &Document) -> Result<RawDocumentBuf> { |
| 111 |
let mut data = Vec::new(); |
| 112 |
doc.to_writer(&mut data).map_err(|e| Error { |
| 113 |
key: None, |
| 114 |
kind: ErrorKind::MalformedValue { |
| 115 |
message: e.to_string(), |
| 116 |
}, |
| 117 |
})?; |
| 118 |
|
| 119 |
Ok(Self { data }) |
| 120 |
} |
| 121 |
|
| 122 |
/// Gets an iterator over the elements in the [`RawDocumentBuf`], which yields |
| 123 |
/// `Result<(&str, RawBson<'_>)>`. |
| 124 |
/// |
| 125 |
/// ``` |
| 126 |
/// # use bson::raw::Error; |
| 127 |
/// use bson::{doc, raw::RawDocumentBuf}; |
| 128 |
/// |
| 129 |
/// let doc = RawDocumentBuf::from_document(&doc! { "ferris": true })?; |
| 130 |
/// |
| 131 |
/// for element in doc.iter() { |
| 132 |
/// let (key, value) = element?; |
| 133 |
/// assert_eq!(key, "ferris"); |
| 134 |
/// assert_eq!(value.as_bool(), Some(true)); |
| 135 |
/// } |
| 136 |
/// # Ok::<(), Error>(()) |
| 137 |
/// ``` |
| 138 |
/// |
| 139 |
/// # Note: |
| 140 |
/// |
| 141 |
/// There is no owning iterator for [`RawDocumentBuf`]. If you need ownership over |
| 142 |
/// elements that might need to allocate, you must explicitly convert |
| 143 |
/// them to owned types yourself. |
| 144 |
pub fn iter(&self) -> Iter<'_> { |
| 145 |
Iter::new(self) |
| 146 |
} |
| 147 |
|
| 148 |
/// Gets an iterator over the elements in the [`RawDocumentBuf`], |
| 149 |
/// which yields `Result<RawElement<'_>>` values. These hold a |
| 150 |
/// reference to the underlying document but do not explicitly |
| 151 |
/// resolve the values. |
| 152 |
/// |
| 153 |
/// This iterator, which underpins the implementation of the |
| 154 |
/// default iterator, produces `RawElement` objects that hold a |
| 155 |
/// view onto the document but do not parse out or construct |
| 156 |
/// values until the `.value()` or `.try_into()` methods are |
| 157 |
/// called. |
| 158 |
/// |
| 159 |
/// # Note: |
| 160 |
/// |
| 161 |
/// There is no owning iterator for [`RawDocumentBuf`]. If you |
| 162 |
/// need ownership over elements that might need to allocate, you |
| 163 |
/// must explicitly convert them to owned types yourself. |
| 164 |
pub fn iter_elements(&self) -> RawIter<'_> { |
| 165 |
RawIter::new(self) |
| 166 |
} |
| 167 |
|
| 168 |
/// Return the contained data as a `Vec<u8>` |
| 169 |
/// |
| 170 |
/// ``` |
| 171 |
/// # use bson::raw::Error; |
| 172 |
/// use bson::{doc, raw::RawDocumentBuf}; |
| 173 |
/// |
| 174 |
/// let doc = RawDocumentBuf::from_document(&doc!{})?; |
| 175 |
/// assert_eq!(doc.into_bytes(), b"\x05\x00\x00\x00\x00".to_vec()); |
| 176 |
/// # Ok::<(), Error>(()) |
| 177 |
/// ``` |
| 178 |
pub fn into_bytes(self) -> Vec<u8> { |
| 179 |
self.data |
| 180 |
} |
| 181 |
|
| 182 |
/// Append a key value pair to the end of the document without checking to see if |
| 183 |
/// the key already exists. |
| 184 |
/// |
| 185 |
/// It is a user error to append the same key more than once to the same document, and it may |
| 186 |
/// result in errors when communicating with MongoDB. |
| 187 |
/// |
| 188 |
/// If the provided key contains an interior null byte, this method will panic. |
| 189 |
/// |
| 190 |
/// ``` |
| 191 |
/// # use bson::raw::Error; |
| 192 |
/// use bson::{doc, raw::RawDocumentBuf}; |
| 193 |
/// |
| 194 |
/// let mut doc = RawDocumentBuf::new(); |
| 195 |
/// doc.append("a string", "some string"); |
| 196 |
/// doc.append("an integer", 12_i32); |
| 197 |
/// |
| 198 |
/// let mut subdoc = RawDocumentBuf::new(); |
| 199 |
/// subdoc.append("a key", true); |
| 200 |
/// doc.append("a document", subdoc); |
| 201 |
/// |
| 202 |
/// let expected = doc! { |
| 203 |
/// "a string": "some string", |
| 204 |
/// "an integer": 12_i32, |
| 205 |
/// "a document": { "a key": true }, |
| 206 |
/// }; |
| 207 |
/// |
| 208 |
/// assert_eq!(doc.to_document()?, expected); |
| 209 |
/// # Ok::<(), Error>(()) |
| 210 |
/// ``` |
| 211 |
pub fn append(&mut self, key: impl AsRef<str>, value: impl Into<RawBson>) { |
| 212 |
let value = value.into(); |
| 213 |
self.append_ref(key, value.as_raw_bson_ref()) |
| 214 |
} |
| 215 |
|
| 216 |
/// Append a key value pair to the end of the document without checking to see if |
| 217 |
/// the key already exists. |
| 218 |
/// |
| 219 |
/// It is a user error to append the same key more than once to the same document, and it may |
| 220 |
/// result in errors when communicating with MongoDB. |
| 221 |
/// |
| 222 |
/// If the provided key contains an interior null byte, this method will panic. |
| 223 |
pub fn append_ref<'a>(&mut self, key: impl AsRef<str>, value: impl Into<RawBsonRef<'a>>) { |
| 224 |
fn append_string(doc: &mut RawDocumentBuf, value: &str) { |
| 225 |
doc.data |
| 226 |
.extend(((value.as_bytes().len() + 1) as i32).to_le_bytes()); |
| 227 |
doc.data.extend(value.as_bytes()); |
| 228 |
doc.data.push(0); |
| 229 |
} |
| 230 |
|
| 231 |
fn append_cstring(doc: &mut RawDocumentBuf, value: &str) { |
| 232 |
if value.contains('\0') { |
| 233 |
panic!("cstr includes interior null byte: {}", value) |
| 234 |
} |
| 235 |
doc.data.extend(value.as_bytes()); |
| 236 |
doc.data.push(0); |
| 237 |
} |
| 238 |
|
| 239 |
let original_len = self.data.len(); |
| 240 |
|
| 241 |
// write the key for the next value to the end |
| 242 |
// the element type will replace the previous null byte terminator of the document |
| 243 |
append_cstring(self, key.as_ref()); |
| 244 |
|
| 245 |
let value = value.into(); |
| 246 |
let element_type = value.element_type(); |
| 247 |
|
| 248 |
match value { |
| 249 |
RawBsonRef::Int32(i) => { |
| 250 |
self.data.extend(i.to_le_bytes()); |
| 251 |
} |
| 252 |
RawBsonRef::String(s) => { |
| 253 |
append_string(self, s); |
| 254 |
} |
| 255 |
RawBsonRef::Document(d) => { |
| 256 |
self.data.extend(d.as_bytes()); |
| 257 |
} |
| 258 |
RawBsonRef::Array(a) => { |
| 259 |
self.data.extend(a.as_bytes()); |
| 260 |
} |
| 261 |
RawBsonRef::Binary(b) => { |
| 262 |
let len = b.len(); |
| 263 |
self.data.extend(len.to_le_bytes()); |
| 264 |
self.data.push(b.subtype.into()); |
| 265 |
if let BinarySubtype::BinaryOld = b.subtype { |
| 266 |
self.data.extend((len - 4).to_le_bytes()) |
| 267 |
} |
| 268 |
self.data.extend(b.bytes); |
| 269 |
} |
| 270 |
RawBsonRef::Boolean(b) => { |
| 271 |
self.data.push(b as u8); |
| 272 |
} |
| 273 |
RawBsonRef::DateTime(dt) => { |
| 274 |
self.data.extend(dt.timestamp_millis().to_le_bytes()); |
| 275 |
} |
| 276 |
RawBsonRef::DbPointer(dbp) => { |
| 277 |
append_string(self, dbp.namespace); |
| 278 |
self.data.extend(dbp.id.bytes()); |
| 279 |
} |
| 280 |
RawBsonRef::Decimal128(d) => { |
| 281 |
self.data.extend(d.bytes()); |
| 282 |
} |
| 283 |
RawBsonRef::Double(d) => { |
| 284 |
self.data.extend(d.to_le_bytes()); |
| 285 |
} |
| 286 |
RawBsonRef::Int64(i) => { |
| 287 |
self.data.extend(i.to_le_bytes()); |
| 288 |
} |
| 289 |
RawBsonRef::RegularExpression(re) => { |
| 290 |
append_cstring(self, re.pattern); |
| 291 |
append_cstring(self, re.options); |
| 292 |
} |
| 293 |
RawBsonRef::JavaScriptCode(js) => { |
| 294 |
append_string(self, js); |
| 295 |
} |
| 296 |
RawBsonRef::JavaScriptCodeWithScope(code_w_scope) => { |
| 297 |
let len = code_w_scope.len(); |
| 298 |
self.data.extend(len.to_le_bytes()); |
| 299 |
append_string(self, code_w_scope.code); |
| 300 |
self.data.extend(code_w_scope.scope.as_bytes()); |
| 301 |
} |
| 302 |
RawBsonRef::Timestamp(ts) => { |
| 303 |
self.data.extend(ts.to_le_bytes()); |
| 304 |
} |
| 305 |
RawBsonRef::ObjectId(oid) => { |
| 306 |
self.data.extend(oid.bytes()); |
| 307 |
} |
| 308 |
RawBsonRef::Symbol(s) => { |
| 309 |
append_string(self, s); |
| 310 |
} |
| 311 |
RawBsonRef::Null | RawBsonRef::Undefined | RawBsonRef::MinKey | RawBsonRef::MaxKey => {} |
| 312 |
} |
| 313 |
|
| 314 |
// update element type |
| 315 |
self.data[original_len - 1] = element_type as u8; |
| 316 |
// append trailing null byte |
| 317 |
self.data.push(0); |
| 318 |
// update length |
| 319 |
let new_len = (self.data.len() as i32).to_le_bytes(); |
| 320 |
self.data[0..4].copy_from_slice(&new_len); |
| 321 |
} |
| 322 |
|
| 323 |
/// Convert this [`RawDocumentBuf`] to a [`Document`], returning an error |
| 324 |
/// if invalid BSON is encountered. |
| 325 |
pub fn to_document(&self) -> Result<Document> { |
| 326 |
self.as_ref().try_into() |
| 327 |
} |
| 328 |
} |
| 329 |
|
| 330 |
impl Default for RawDocumentBuf { |
| 331 |
fn default() -> Self { |
| 332 |
Self::new() |
| 333 |
} |
| 334 |
} |
| 335 |
|
| 336 |
impl<'de> Deserialize<'de> for RawDocumentBuf { |
| 337 |
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error> |
| 338 |
where |
| 339 |
D: serde::Deserializer<'de>, |
| 340 |
{ |
| 341 |
Ok(OwnedOrBorrowedRawDocument::deserialize(deserializer)?.into_owned()) |
| 342 |
} |
| 343 |
} |
| 344 |
|
| 345 |
impl Serialize for RawDocumentBuf { |
| 346 |
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> |
| 347 |
where |
| 348 |
S: serde::Serializer, |
| 349 |
{ |
| 350 |
let doc: &RawDocument = self.deref(); |
| 351 |
doc.serialize(serializer) |
| 352 |
} |
| 353 |
} |
| 354 |
|
| 355 |
impl std::fmt::Debug for RawDocumentBuf { |
| 356 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 357 |
f.debug_struct("RawDocumentBuf") |
| 358 |
.field("data", &hex::encode(&self.data)) |
| 359 |
.finish() |
| 360 |
} |
| 361 |
} |
| 362 |
|
| 363 |
impl<'a> From<RawDocumentBuf> for Cow<'a, RawDocument> { |
| 364 |
fn from(rd: RawDocumentBuf) -> Self { |
| 365 |
Cow::Owned(rd) |
| 366 |
} |
| 367 |
} |
| 368 |
|
| 369 |
impl<'a> From<&'a RawDocumentBuf> for Cow<'a, RawDocument> { |
| 370 |
fn from(rd: &'a RawDocumentBuf) -> Self { |
| 371 |
Cow::Borrowed(rd.as_ref()) |
| 372 |
} |
| 373 |
} |
| 374 |
|
| 375 |
impl TryFrom<RawDocumentBuf> for Document { |
| 376 |
type Error = Error; |
| 377 |
|
| 378 |
fn try_from(raw: RawDocumentBuf) -> Result<Document> { |
| 379 |
Document::try_from(raw.as_ref()) |
| 380 |
} |
| 381 |
} |
| 382 |
|
| 383 |
impl TryFrom<&Document> for RawDocumentBuf { |
| 384 |
type Error = Error; |
| 385 |
|
| 386 |
fn try_from(doc: &Document) -> Result<RawDocumentBuf> { |
| 387 |
RawDocumentBuf::from_document(doc) |
| 388 |
} |
| 389 |
} |
| 390 |
|
| 391 |
impl<'a> IntoIterator for &'a RawDocumentBuf { |
| 392 |
type IntoIter = Iter<'a>; |
| 393 |
type Item = Result<(&'a str, RawBsonRef<'a>)>; |
| 394 |
|
| 395 |
fn into_iter(self) -> Iter<'a> { |
| 396 |
self.iter() |
| 397 |
} |
| 398 |
} |
| 399 |
|
| 400 |
impl AsRef<RawDocument> for RawDocumentBuf { |
| 401 |
fn as_ref(&self) -> &RawDocument { |
| 402 |
RawDocument::new_unchecked(&self.data) |
| 403 |
} |
| 404 |
} |
| 405 |
|
| 406 |
impl Deref for RawDocumentBuf { |
| 407 |
type Target = RawDocument; |
| 408 |
|
| 409 |
fn deref(&self) -> &Self::Target { |
| 410 |
RawDocument::new_unchecked(&self.data) |
| 411 |
} |
| 412 |
} |
| 413 |
|
| 414 |
impl Borrow<RawDocument> for RawDocumentBuf { |
| 415 |
fn borrow(&self) -> &RawDocument { |
| 416 |
self.deref() |
| 417 |
} |
| 418 |
} |
| 419 |
|
| 420 |
impl<S: AsRef<str>, T: Into<RawBson>> FromIterator<(S, T)> for RawDocumentBuf { |
| 421 |
fn from_iter<I: IntoIterator<Item = (S, T)>>(iter: I) -> Self { |
| 422 |
let mut buf = RawDocumentBuf::new(); |
| 423 |
for (k, v) in iter { |
| 424 |
buf.append(k, v); |
| 425 |
} |
| 426 |
buf |
| 427 |
} |
| 428 |
} |