Struct rbson::RawDocumentBuf
source · [−]pub struct RawDocumentBuf { /* private fields */ }
Expand description
An owned BSON document (akin to std::path::PathBuf
), backed by a buffer of raw BSON bytes.
This can be created from a Vec<u8>
or a crate::Document
.
Accessing elements within a RawDocumentBuf
is similar to element access in
crate::Document
, but because the contents are parsed during iteration instead of at creation
time, format errors can happen at any time during use.
Iterating over a RawDocumentBuf
yields either an error or a key-value pair that borrows from
the original document without making any additional allocations.
use bson::raw::RawDocumentBuf;
let doc = RawDocumentBuf::new(b"\x13\x00\x00\x00\x02hi\x00\x06\x00\x00\x00y'all\x00\x00".to_vec())?;
let mut iter = doc.iter();
let (key, value) = iter.next().unwrap()?;
assert_eq!(key, "hi");
assert_eq!(value.as_str(), Some("y'all"));
assert!(iter.next().is_none());
This type implements Deref
to RawDocument
, meaning that all methods on RawDocument
are
available on RawDocumentBuf
values as well. This includes RawDocument::get
or any of the
type-specific getters, such as [RawDocument::get_object_id
] or RawDocument::get_str
. Note
that accessing elements is an O(N) operation, as it requires iterating through the document from
the beginning to find the requested key.
use bson::raw::RawDocumentBuf;
let doc = RawDocumentBuf::new(b"\x13\x00\x00\x00\x02hi\x00\x06\x00\x00\x00y'all\x00\x00".to_vec())?;
assert_eq!(doc.get_str("hi")?, "y'all");
Implementations
sourceimpl RawDocumentBuf
impl RawDocumentBuf
sourcepub fn new(data: Vec<u8>) -> Result<RawDocumentBuf>
pub fn new(data: Vec<u8>) -> Result<RawDocumentBuf>
Constructs a new RawDocumentBuf
, validating only the
following invariants:
data
is at least five bytes long (the minimum for a valid BSON document)- the initial four bytes of
data
accurately represent the length of the bytes as required by the BSON spec. - the last byte of
data
is a 0
Note that the internal structure of the bytes representing the BSON elements is not validated at all by this method. If the bytes do not conform to the BSON spec, then method calls on the RawDocument will return Errors where appropriate.
let doc = RawDocumentBuf::new(b"\x05\0\0\0\0".to_vec())?;
sourcepub fn from_document(doc: &Document) -> Result<RawDocumentBuf>
pub fn from_document(doc: &Document) -> Result<RawDocumentBuf>
Create a RawDocumentBuf
from a Document
.
use bson::{doc, oid::ObjectId, raw::RawDocumentBuf};
let document = doc! {
"_id": ObjectId::new(),
"name": "Herman Melville",
"title": "Moby-Dick",
};
let doc = RawDocumentBuf::from_document(&document)?;
sourcepub fn iter(&self) -> Iter<'_>ⓘNotable traits for Iter<'a>impl<'a> Iterator for Iter<'a> type Item = Result<(&'a str, RawBson<'a>)>;
pub fn iter(&self) -> Iter<'_>ⓘNotable traits for Iter<'a>impl<'a> Iterator for Iter<'a> type Item = Result<(&'a str, RawBson<'a>)>;
Gets an iterator over the elements in the RawDocumentBuf
, which yields
Result<(&str, RawBson<'_>)>
.
use bson::{doc, raw::RawDocumentBuf};
let doc = RawDocumentBuf::from_document(&doc! { "ferris": true })?;
for element in doc.iter() {
let (key, value) = element?;
assert_eq!(key, "ferris");
assert_eq!(value.as_bool(), Some(true));
}
Note:
There is no owning iterator for RawDocumentBuf
. If you need ownership over
elements that might need to allocate, you must explicitly convert
them to owned types yourself.
sourcepub fn into_vec(self) -> Vec<u8>ⓘNotable traits for Vec<u8, A>impl<A> Write for Vec<u8, A> where
A: Allocator,
pub fn into_vec(self) -> Vec<u8>ⓘNotable traits for Vec<u8, A>impl<A> Write for Vec<u8, A> where
A: Allocator,
A: Allocator,
Return the contained data as a Vec<u8>
use bson::{doc, raw::RawDocumentBuf};
let doc = RawDocumentBuf::from_document(&doc!{})?;
assert_eq!(doc.into_vec(), b"\x05\x00\x00\x00\x00".to_vec());
Methods from Deref<Target = RawDocument>
sourcepub fn to_raw_document_buf(&self) -> RawDocumentBuf
pub fn to_raw_document_buf(&self) -> RawDocumentBuf
Creates a new RawDocument
with an owned copy of the BSON bytes.
use bson::raw::{RawDocument, RawDocumentBuf, Error};
let data = b"\x05\0\0\0\0";
let doc_ref = RawDocument::new(data)?;
let doc: RawDocumentBuf = doc_ref.to_raw_document_buf();
sourcepub fn get(&self, key: impl AsRef<str>) -> Result<Option<RawBson<'_>>>
pub fn get(&self, key: impl AsRef<str>) -> Result<Option<RawBson<'_>>>
Gets a reference to the value corresponding to the given key by iterating until the key is found.
use bson::{doc, oid::ObjectId, raw::{RawDocumentBuf, RawBson}};
let doc = RawDocumentBuf::from_document(&doc! {
"_id": ObjectId::new(),
"f64": 2.5,
})?;
let element = doc.get("f64")?.expect("finding key f64");
assert_eq!(element.as_f64(), Some(2.5));
assert!(doc.get("unknown")?.is_none());
sourcepub fn get_f64(&self, key: impl AsRef<str>) -> ValueAccessResult<f64>
pub fn get_f64(&self, key: impl AsRef<str>) -> ValueAccessResult<f64>
Gets a reference to the BSON double value corresponding to a given key or returns an error if the key corresponds to a value which isn’t a double.
use bson::raw::{ValueAccessErrorKind, RawDocumentBuf};
use bson::doc;
let doc = RawDocumentBuf::from_document(&doc! {
"bool": true,
"f64": 2.5,
})?;
assert_eq!(doc.get_f64("f64")?, 2.5);
assert!(matches!(doc.get_f64("bool").unwrap_err().kind, ValueAccessErrorKind::UnexpectedType { .. }));
assert!(matches!(doc.get_f64("unknown").unwrap_err().kind, ValueAccessErrorKind::NotPresent));
sourcepub fn get_str(&self, key: impl AsRef<str>) -> ValueAccessResult<&str>
pub fn get_str(&self, key: impl AsRef<str>) -> ValueAccessResult<&str>
Gets a reference to the string value corresponding to a given key or returns an error if the key corresponds to a value which isn’t a string.
use bson::{doc, raw::{RawDocumentBuf, ValueAccessErrorKind}};
let doc = RawDocumentBuf::from_document(&doc! {
"string": "hello",
"bool": true,
})?;
assert_eq!(doc.get_str("string")?, "hello");
assert!(matches!(doc.get_str("bool").unwrap_err().kind, ValueAccessErrorKind::UnexpectedType { .. }));
assert!(matches!(doc.get_str("unknown").unwrap_err().kind, ValueAccessErrorKind::NotPresent));
sourcepub fn get_document(
&self,
key: impl AsRef<str>
) -> ValueAccessResult<&RawDocument>
pub fn get_document(
&self,
key: impl AsRef<str>
) -> ValueAccessResult<&RawDocument>
Gets a reference to the document value corresponding to a given key or returns an error if the key corresponds to a value which isn’t a document.
use bson::{doc, raw::{ValueAccessErrorKind, RawDocumentBuf}};
let doc = RawDocumentBuf::from_document(&doc! {
"doc": { "key": "value"},
"bool": true,
})?;
assert_eq!(doc.get_document("doc")?.get_str("key")?, "value");
assert!(matches!(doc.get_document("bool").unwrap_err().kind, ValueAccessErrorKind::UnexpectedType { .. }));
assert!(matches!(doc.get_document("unknown").unwrap_err().kind, ValueAccessErrorKind::NotPresent));
sourcepub fn get_array(&self, key: impl AsRef<str>) -> ValueAccessResult<&RawArray>
pub fn get_array(&self, key: impl AsRef<str>) -> ValueAccessResult<&RawArray>
Gets a reference to the array value corresponding to a given key or returns an error if the key corresponds to a value which isn’t an array.
use bson::{doc, raw::{RawDocumentBuf, ValueAccessErrorKind}};
let doc = RawDocumentBuf::from_document(&doc! {
"array": [true, 3],
"bool": true,
})?;
let mut arr_iter = doc.get_array("array")?.into_iter();
let _: bool = arr_iter.next().unwrap()?.as_bool().unwrap();
let _: i32 = arr_iter.next().unwrap()?.as_i32().unwrap();
assert!(arr_iter.next().is_none());
assert!(doc.get_array("bool").is_err());
assert!(matches!(doc.get_array("unknown").unwrap_err().kind, ValueAccessErrorKind::NotPresent));
sourcepub fn get_binary(
&self,
key: impl AsRef<str>
) -> ValueAccessResult<RawBinary<'_>>
pub fn get_binary(
&self,
key: impl AsRef<str>
) -> ValueAccessResult<RawBinary<'_>>
Gets a reference to the BSON binary value corresponding to a given key or returns an error if the key corresponds to a value which isn’t a binary value.
use bson::{
doc,
raw::{ValueAccessErrorKind, RawDocumentBuf, RawBinary},
spec::BinarySubtype,
Binary,
};
let doc = RawDocumentBuf::from_document(&doc! {
"binary": Binary { subtype: BinarySubtype::Generic, bytes: vec![1, 2, 3] },
"bool": true,
})?;
assert_eq!(&doc.get_binary("binary")?.bytes, &[1, 2, 3]);
assert!(matches!(doc.get_binary("bool").unwrap_err().kind, ValueAccessErrorKind::UnexpectedType { .. }));
assert!(matches!(doc.get_binary("unknown").unwrap_err().kind, ValueAccessErrorKind::NotPresent));
sourcepub fn get_bool(&self, key: impl AsRef<str>) -> ValueAccessResult<bool>
pub fn get_bool(&self, key: impl AsRef<str>) -> ValueAccessResult<bool>
Gets a reference to the boolean value corresponding to a given key or returns an error if the key corresponds to a value which isn’t a boolean.
use bson::{doc, oid::ObjectId, raw::{RawDocumentBuf, ValueAccessErrorKind}};
let doc = RawDocumentBuf::from_document(&doc! {
"_id": ObjectId::new(),
"bool": true,
})?;
assert!(doc.get_bool("bool")?);
assert!(matches!(doc.get_bool("_id").unwrap_err().kind, ValueAccessErrorKind::UnexpectedType { .. }));
assert!(matches!(doc.get_bool("unknown").unwrap_err().kind, ValueAccessErrorKind::NotPresent));
sourcepub fn get_datetime(&self, key: impl AsRef<str>) -> ValueAccessResult<DateTime>
pub fn get_datetime(&self, key: impl AsRef<str>) -> ValueAccessResult<DateTime>
Gets a reference to the BSON DateTime value corresponding to a given key or returns an error if the key corresponds to a value which isn’t a DateTime.
use bson::{doc, raw::{ValueAccessErrorKind, RawDocumentBuf}, DateTime};
let dt = DateTime::now();
let doc = RawDocumentBuf::from_document(&doc! {
"created_at": dt,
"bool": true,
})?;
assert_eq!(doc.get_datetime("created_at")?, dt);
assert!(matches!(doc.get_datetime("bool").unwrap_err().kind, ValueAccessErrorKind::UnexpectedType { .. }));
assert!(matches!(doc.get_datetime("unknown").unwrap_err().kind, ValueAccessErrorKind::NotPresent));
sourcepub fn get_timestamp(&self, key: impl AsRef<str>) -> ValueAccessResult<Timestamp>
pub fn get_timestamp(&self, key: impl AsRef<str>) -> ValueAccessResult<Timestamp>
Gets a reference to the BSON timestamp value corresponding to a given key or returns an error if the key corresponds to a value which isn’t a timestamp.
use bson::{doc, Timestamp, raw::{RawDocumentBuf, ValueAccessErrorKind}};
let doc = RawDocumentBuf::from_document(&doc! {
"bool": true,
"ts": Timestamp { time: 649876543, increment: 9 },
})?;
let timestamp = doc.get_timestamp("ts")?;
assert_eq!(timestamp.time, 649876543);
assert_eq!(timestamp.increment, 9);
assert!(matches!(doc.get_timestamp("bool").unwrap_err().kind, ValueAccessErrorKind::UnexpectedType { .. }));
assert!(matches!(doc.get_timestamp("unknown").unwrap_err().kind, ValueAccessErrorKind::NotPresent));
sourcepub fn get_i32(&self, key: impl AsRef<str>) -> ValueAccessResult<i32>
pub fn get_i32(&self, key: impl AsRef<str>) -> ValueAccessResult<i32>
Gets a reference to the BSON int32 value corresponding to a given key or returns an error if the key corresponds to a value which isn’t a 32-bit integer.
use bson::{doc, raw::{RawDocumentBuf, ValueAccessErrorKind}};
let doc = RawDocumentBuf::from_document(&doc! {
"bool": true,
"i32": 1_000_000,
})?;
assert_eq!(doc.get_i32("i32")?, 1_000_000);
assert!(matches!(doc.get_i32("bool").unwrap_err().kind, ValueAccessErrorKind::UnexpectedType { ..}));
assert!(matches!(doc.get_i32("unknown").unwrap_err().kind, ValueAccessErrorKind::NotPresent));
sourcepub fn get_i64(&self, key: impl AsRef<str>) -> ValueAccessResult<i64>
pub fn get_i64(&self, key: impl AsRef<str>) -> ValueAccessResult<i64>
Gets a reference to the BSON int64 value corresponding to a given key or returns an error if the key corresponds to a value which isn’t a 64-bit integer.
use bson::{doc, raw::{ValueAccessErrorKind, RawDocumentBuf}};
let doc = RawDocumentBuf::from_document(&doc! {
"bool": true,
"i64": 9223372036854775807_i64,
})?;
assert_eq!(doc.get_i64("i64")?, 9223372036854775807);
assert!(matches!(doc.get_i64("bool").unwrap_err().kind, ValueAccessErrorKind::UnexpectedType { .. }));
assert!(matches!(doc.get_i64("unknown").unwrap_err().kind, ValueAccessErrorKind::NotPresent));
sourcepub fn as_bytes(&self) -> &[u8]ⓘNotable traits for &mut [u8]impl Write for &mut [u8]impl Read for &[u8]
pub fn as_bytes(&self) -> &[u8]ⓘNotable traits for &mut [u8]impl Write for &mut [u8]impl Read for &[u8]
Return a reference to the contained data as a &[u8]
use bson::{doc, raw::RawDocumentBuf};
let docbuf = RawDocumentBuf::from_document(&doc!{})?;
assert_eq!(docbuf.as_bytes(), b"\x05\x00\x00\x00\x00");
Trait Implementations
sourceimpl AsRef<RawDocument> for RawDocumentBuf
impl AsRef<RawDocument> for RawDocumentBuf
sourcefn as_ref(&self) -> &RawDocument
fn as_ref(&self) -> &RawDocument
Converts this type into a shared reference of the (usually inferred) input type.
sourceimpl Borrow<RawDocument> for RawDocumentBuf
impl Borrow<RawDocument> for RawDocumentBuf
sourcefn borrow(&self) -> &RawDocument
fn borrow(&self) -> &RawDocument
Immutably borrows from an owned value. Read more
sourceimpl Clone for RawDocumentBuf
impl Clone for RawDocumentBuf
sourcefn clone(&self) -> RawDocumentBuf
fn clone(&self) -> RawDocumentBuf
Returns a copy of the value. Read more
1.0.0 · sourcefn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from source
. Read more
sourceimpl Debug for RawDocumentBuf
impl Debug for RawDocumentBuf
sourceimpl Deref for RawDocumentBuf
impl Deref for RawDocumentBuf
type Target = RawDocument
type Target = RawDocument
The resulting type after dereferencing.
sourceimpl<'de> Deserialize<'de> for RawDocumentBuf
impl<'de> Deserialize<'de> for RawDocumentBuf
sourcefn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where
D: Deserializer<'de>,
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where
D: Deserializer<'de>,
Deserialize this value from the given Serde deserializer. Read more
sourceimpl<'a> From<&'a RawDocumentBuf> for Cow<'a, RawDocument>
impl<'a> From<&'a RawDocumentBuf> for Cow<'a, RawDocument>
sourcefn from(rd: &'a RawDocumentBuf) -> Self
fn from(rd: &'a RawDocumentBuf) -> Self
Converts to this type from the input type.
sourceimpl<'a> From<RawDocumentBuf> for Cow<'a, RawDocument>
impl<'a> From<RawDocumentBuf> for Cow<'a, RawDocument>
sourcefn from(rd: RawDocumentBuf) -> Self
fn from(rd: RawDocumentBuf) -> Self
Converts to this type from the input type.
sourceimpl<'a> IntoIterator for &'a RawDocumentBuf
impl<'a> IntoIterator for &'a RawDocumentBuf
sourceimpl PartialEq<RawDocumentBuf> for RawDocumentBuf
impl PartialEq<RawDocumentBuf> for RawDocumentBuf
sourcefn eq(&self, other: &RawDocumentBuf) -> bool
fn eq(&self, other: &RawDocumentBuf) -> bool
This method tests for self
and other
values to be equal, and is used
by ==
. Read more
sourcefn ne(&self, other: &RawDocumentBuf) -> bool
fn ne(&self, other: &RawDocumentBuf) -> bool
This method tests for !=
.
sourceimpl Serialize for RawDocumentBuf
impl Serialize for RawDocumentBuf
sourceimpl TryFrom<RawDocumentBuf> for Document
impl TryFrom<RawDocumentBuf> for Document
impl StructuralPartialEq for RawDocumentBuf
Auto Trait Implementations
impl RefUnwindSafe for RawDocumentBuf
impl Send for RawDocumentBuf
impl Sync for RawDocumentBuf
impl Unpin for RawDocumentBuf
impl UnwindSafe for RawDocumentBuf
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more