[−][src]Struct rawbson::DocBuf
A BSON document, stored as raw binary data on the heap. This can be created from
a Vec<u8>
or a bson::Document
.
Accessing elements within the DocBuf
is similar to element access in bson::Document,
but as the contents are parsed during iteration, instead of at creation time, format
errors can happen at any time during use, instead of at creation time.
DocBuf can be iterated over, yielding a Result containing key-value pairs that borrow from the DocBuf instead of allocating, when necessary.
let docbuf = DocBuf::new(b"\x13\x00\x00\x00\x02hi\x00\x06\x00\x00\x00y'all\x00\x00".to_vec())?; let mut iter = docbuf.iter(); let (key, value) = iter.next().unwrap()?; assert_eq!(key, "hi"); assert_eq!(value.as_str(), Ok("y'all")); assert!(iter.next().is_none());
Individual elements can be accessed using docbuf.get(&key)
, or any of
the get_*
methods, like docbuf.get_object_id(&key)
, and
docbuf.get_str(&str)
. Accessing elements is an O(N) operation,
as it requires iterating through the document from the beginning to find the requested
key.
let docbuf = DocBuf::new(b"\x13\x00\x00\x00\x02hi\x00\x06\x00\x00\x00y'all\x00\x00".to_vec())?; assert_eq!(docbuf.get_str("hi")?, Some("y'all"));
Implementations
impl DocBuf
[src]
pub fn new(data: Vec<u8>) -> RawResult<DocBuf>
[src]
Create a new DocBuf
from the provided Vec
.
The data is checked for a declared length equal to the length of the Vec, and a trailing NUL byte. Other validation is deferred to access time.
let docbuf: DocBuf = DocBuf::new(b"\x05\0\0\0\0".to_vec())?;
pub fn from_document(doc: &Document) -> DocBuf
[src]
Create a DocBuf from a bson::Document.
use bson::{doc, oid}; let document = doc! { "_id": oid::ObjectId::new(), "name": "Herman Melville", "title": "Moby-Dick", }; let docbuf: DocBuf = DocBuf::from_document(&document);
pub unsafe fn new_unchecked(data: Vec<u8>) -> DocBuf
[src]
Create a DocBuf from an owned Vec
let docbuf: DocBuf = unsafe { DocBuf::new_unchecked(b"\x05\0\0\0\0".to_vec()) };
Safety
The provided bytes must have a valid length marker, and be NUL terminated.
pub fn as_docref(&self) -> &Doc
[src]
use docbuf.as_ref() instead
Return a &Doc
borrowing from the data contained in self.
Deprecation
DocRef is now a deprecated type alias for Doc. DocBuf can dereference to &Doc directly, or be converted using AsRef::as_ref, so this function is unnecessary.
let docbuf = DocBuf::new(b"\x13\x00\x00\x00\x02hi\x00\x06\x00\x00\x00y'all\x00\x00".to_vec())?; let docref: DocRef = docbuf.as_docref();
pub fn iter(&self) -> DocIter<'_>ⓘ
[src]
Return an iterator over the elements in the DocBuf
, borrowing data.
The associated item type is Result<&str, Element<'_>>
. An error is
returned if data is malformed.
use bson::doc; let docbuf = DocBuf::from_document(&doc! { "ferris": true }); for element in docbuf.iter() { let (key, value): (&str, elem::Element) = element?; assert_eq!(key, "ferris"); assert_eq!(value.as_bool()?, true); }
Note:
There is no owning iterator for DocBuf. If you need ownership over elements that might need to allocate, you must explicitly convert them to owned types yourself.
pub fn into_inner(self) -> Vec<u8>
[src]
Return the contained data as a Vec<u8>
use bson::doc; let docbuf = DocBuf::from_document(&doc!{}); assert_eq!(docbuf.into_inner(), b"\x05\x00\x00\x00\x00".to_vec());
Methods from Deref<Target = Doc>
pub fn to_docbuf(&self) -> DocBuf
[src]
Create a new DocBuf with an owned copy of the data in self.
use rawbson::DocBuf; let data = b"\x05\0\0\0\0"; let doc = Doc::new(data)?; let docbuf: DocBuf = data.to_docbuf();
pub fn get<'a>(&'a self, key: &str) -> RawResult<Option<Element<'a>>>
[src]
Get an element from the document. Finding a particular key requires iterating over the document from the beginning, so this is an O(N) operation.
Returns an error if the document is malformed. Returns Ok(None)
if the key is not found in the document.
use bson::{doc, oid::ObjectId}; let docbuf = DocBuf::from_document(&doc! { "_id": ObjectId::new(), "f64": 2.5, }); let element = docbuf.get("f64")?.expect("finding key f64"); assert_eq!(element.as_f64(), Ok(2.5)); assert!(docbuf.get("unknown")?.is_none());
pub fn get_f64(&self, key: &str) -> RawResult<Option<f64>>
[src]
Get an element from the document, and convert it to f64.
Returns an error if the document is malformed, or if the retrieved value
is not an f64. Returns Ok(None)
if the key is not found in the document.
use bson::doc; let docbuf = DocBuf::from_document(&doc! { "bool": true, "f64": 2.5, }); assert_eq!(docbuf.get_f64("f64"), Ok(Some(2.5))); assert_eq!(docbuf.get_f64("bool"), Err(RawError::UnexpectedType)); assert_eq!(docbuf.get_f64("unknown"), Ok(None));
pub fn get_str<'a>(&'a self, key: &str) -> RawResult<Option<&'a str>>
[src]
Get an element from the document, and convert it to a &str.
The returned &str is a borrowed reference into the DocBuf. To use it beyond the lifetime of self, call to_docbuf() on it.
Returns an error if the document is malformed or if the retrieved value
is not a string. Returns Ok(None)
if the key is not found in the
document.
use bson::doc; let docbuf = DocBuf::from_document(&doc! { "string": "hello", "bool": true, }); assert_eq!(docbuf.get_str("string"), Ok(Some("hello"))); assert_eq!(docbuf.get_str("bool"), Err(RawError::UnexpectedType)); assert_eq!(docbuf.get_str("unknown"), Ok(None));
pub fn get_document<'a>(&'a self, key: &str) -> RawResult<Option<&'a Doc>>
[src]
Get an element from the document, and convert it to a Doc.
The returned Doc is a borrowed reference into self. To use it beyond the lifetime of self, call to_owned() on it.
Returns an error if the document is malformed or if the retrieved value
is not a document. Returns Ok(None)
if the key is not found in the
document.
use bson::doc; let docbuf = DocBuf::from_document(&doc! { "doc": { "key": "value"}, "bool": true, }); assert_eq!(docbuf.get_document("doc")?.expect("finding key doc").get_str("key"), Ok(Some("value"))); assert_eq!(docbuf.get_document("bool").unwrap_err(), RawError::UnexpectedType); assert!(docbuf.get_document("unknown")?.is_none());
pub fn get_array<'a>(&'a self, key: &str) -> RawResult<Option<&'a Array>>
[src]
Get an element from the document, and convert it to an ArrayRef.
The returned ArrayRef is a borrowed reference into the DocBuf.
Returns an error if the document is malformed or if the retrieved value
is not a document. Returns Ok(None)
if the key is not found in the
document.
use bson::doc; let docbuf = DocBuf::from_document(&doc! { "array": [true, 3, null], "bool": true, }); let mut arriter = docbuf.get_array("array")?.expect("finding key array").into_iter(); let _: bool = arriter.next().unwrap()?.as_bool()?; let _: i32 = arriter.next().unwrap()?.as_i32()?; let () = arriter.next().unwrap()?.as_null()?; assert!(arriter.next().is_none()); assert!(docbuf.get_array("bool").is_err()); assert!(docbuf.get_array("unknown")?.is_none());
pub fn get_binary<'a>(
&'a self,
key: &str
) -> RawResult<Option<RawBsonBinary<'a>>>
[src]
&'a self,
key: &str
) -> RawResult<Option<RawBsonBinary<'a>>>
Get an element from the document, and convert it to an elem::RawBsonBinary.
The returned RawBsonBinary is a borrowed reference into the DocBuf.
Returns an error if the document is malformed or if the retrieved value
is not binary data. Returns Ok(None)
if the key is not found in the
document.
use bson::{doc, Binary, spec::BinarySubtype}; let docbuf = DocBuf::from_document(&doc! { "binary": Binary { subtype: BinarySubtype::Generic, bytes: vec![1, 2, 3] }, "bool": true, }); assert_eq!(docbuf.get_binary("binary")?.map(elem::RawBsonBinary::as_bytes), Some(&[1, 2, 3][..])); assert_eq!(docbuf.get_binary("bool").unwrap_err(), RawError::UnexpectedType); assert!(docbuf.get_binary("unknown")?.is_none());
pub fn get_object_id(&self, key: &str) -> RawResult<Option<ObjectId>>
[src]
Get an element from the document, and convert it to a bson::oid::ObjectId.
Returns an error if the document is malformed or if the retrieved value
is not an object ID. Returns Ok(None)
if the key is not found in the
document.
use bson::{doc, oid::ObjectId}; let docbuf = DocBuf::from_document(&doc! { "_id": ObjectId::new(), "bool": true, }); let _: ObjectId = docbuf.get_object_id("_id")?.unwrap(); assert_eq!(docbuf.get_object_id("bool").unwrap_err(), RawError::UnexpectedType); assert!(docbuf.get_object_id("unknown")?.is_none());
pub fn get_bool(&self, key: &str) -> RawResult<Option<bool>>
[src]
Get an element from the document, and convert it to a bool.
Returns an error if the document is malformed or if the retrieved value
is not a boolean. Returns Ok(None)
if the key is not found in the
document.
use bson::{doc, oid::ObjectId}; let docbuf = DocBuf::from_document(&doc! { "_id": ObjectId::new(), "bool": true, }); assert!(docbuf.get_bool("bool")?.unwrap()); assert_eq!(docbuf.get_bool("_id").unwrap_err(), RawError::UnexpectedType); assert!(docbuf.get_object_id("unknown")?.is_none());
pub fn get_datetime(&self, key: &str) -> RawResult<Option<DateTime<Utc>>>
[src]
Get an element from the document, and convert it to a chrono::DateTime.
Returns an error if the document is malformed or if the retrieved value
is not a boolean. Returns Ok(None)
if the key is not found in the
document.
use bson::doc; use chrono::{Utc, Datelike, TimeZone}; let docbuf = DocBuf::from_document(&doc! { "created_at": Utc.ymd(2020, 3, 15).and_hms(17, 0, 0), "bool": true, }); assert_eq!(docbuf.get_datetime("created_at")?.unwrap().year(), 2020); assert_eq!(docbuf.get_datetime("bool").unwrap_err(), RawError::UnexpectedType); assert!(docbuf.get_datetime("unknown")?.is_none());
pub fn get_null(&self, key: &str) -> RawResult<Option<()>>
[src]
Get an element from the document, and convert it to the ()
type.
Returns an error if the document is malformed or if the retrieved value
is not null. Returns Ok(None)
if the key is not found in the
document.
There is not much reason to use the () value, so this method mostly exists for consistency with other element types, and as a way to assert type of the element.
use bson::doc; let docbuf = DocBuf::from_document(&doc! { "null": null, "bool": true, }); docbuf.get_null("null")?.unwrap(); assert_eq!(docbuf.get_null("bool").unwrap_err(), RawError::UnexpectedType); assert!(docbuf.get_null("unknown")?.is_none());
pub fn get_regex<'a>(&'a self, key: &str) -> RawResult<Option<RawBsonRegex<'a>>>
[src]
Get an element from the document, and convert it to an elem::RawBsonRegex.
The RawBsonRegex borrows data from the DocBuf.
Returns an error if the document is malformed or if the retrieved value
is not a regex. Returns Ok(None)
if the key is not found in the
document.
use bson::{doc, Regex}; let docbuf = DocBuf::from_document(&doc! { "regex": Regex { pattern: String::from(r"end\s*$"), options: String::from("i"), }, "bool": true, }); assert_eq!(docbuf.get_regex("regex")?.unwrap().pattern(), r"end\s*$"); assert_eq!(docbuf.get_regex("regex")?.unwrap().options(), "i"); assert_eq!(docbuf.get_regex("bool").unwrap_err(), RawError::UnexpectedType); assert!(docbuf.get_regex("unknown")?.is_none());
pub fn get_javascript<'a>(&'a self, key: &str) -> RawResult<Option<&'a str>>
[src]
Get an element from the document, and convert it to an &str representing the javascript element type.
The &str borrows data from the DocBuf. If you need an owned copy of the data, you should call .to_owned() on the result.
Returns an error if the document is malformed or if the retrieved value
is not a javascript code object. Returns Ok(None)
if the key is not found
in the document.
use bson::{doc, Bson}; let docbuf = DocBuf::from_document(&doc! { "js": Bson::JavaScriptCode(String::from("console.log(\"hi y'all\");")), "bool": true, }); assert_eq!(docbuf.get_javascript("js")?, Some("console.log(\"hi y'all\");")); assert_eq!(docbuf.get_javascript("bool").unwrap_err(), RawError::UnexpectedType); assert!(docbuf.get_javascript("unknown")?.is_none());
pub fn get_symbol<'a>(&'a self, key: &str) -> RawResult<Option<&'a str>>
[src]
Get an element from the document, and convert it to an &str representing the symbol element type.
The &str borrows data from the DocBuf. If you need an owned copy of the data, you should call .to_owned() on the result.
Returns an error if the document is malformed or if the retrieved value
is not a symbol object. Returns Ok(None)
if the key is not found
in the document.
use bson::{doc, Bson}; let docbuf = DocBuf::from_document(&doc! { "symbol": Bson::Symbol(String::from("internal")), "bool": true, }); assert_eq!(docbuf.get_symbol("symbol")?, Some("internal")); assert_eq!(docbuf.get_symbol("bool").unwrap_err(), RawError::UnexpectedType); assert!(docbuf.get_symbol("unknown")?.is_none());
pub fn get_javascript_with_scope<'a>(
&'a self,
key: &str
) -> RawResult<Option<(&'a str, &'a Doc)>>
[src]
&'a self,
key: &str
) -> RawResult<Option<(&'a str, &'a Doc)>>
Get an element from the document, and extract the data as a javascript code with scope.
The return value is a (&str, &Doc)
where the &str represents the javascript code,
and the &Doc
represents the scope. Both elements borrow data from the DocBuf.
If you need an owned copy of the data, you should call js.to_owned() on
the code or scope.to_docbuf() on the scope.
Returns an error if the document is malformed or if the retrieved value
is not a javascript code with scope object. Returns Ok(None)
if the key is not found
in the document.
use bson::{doc, JavaScriptCodeWithScope}; let docbuf = DocBuf::from_document(&doc! { "js": JavaScriptCodeWithScope { code: String::from("console.log(\"i:\", i);"), scope: doc!{"i": 42}, }, "bool": true, }); let (js, scope) = docbuf.get_javascript_with_scope("js")?.unwrap(); assert_eq!(js, "console.log(\"i:\", i);"); assert_eq!(scope.get_i32("i")?.unwrap(), 42); assert_eq!(docbuf.get_javascript_with_scope("bool").unwrap_err(), RawError::UnexpectedType); assert!(docbuf.get_javascript_with_scope("unknown")?.is_none());
pub fn get_i32(&self, key: &str) -> RawResult<Option<i32>>
[src]
Get an element from the document, and convert it to i32.
Returns an error if the document is malformed, or if the retrieved value
is not an i32. Returns Ok(None)
if the key is not found in the document.
use bson::doc; let docbuf = DocBuf::from_document(&doc! { "bool": true, "i32": 1_000_000, }); assert_eq!(docbuf.get_i32("i32"), Ok(Some(1_000_000))); assert_eq!(docbuf.get_i32("bool"), Err(RawError::UnexpectedType)); assert_eq!(docbuf.get_i32("unknown"), Ok(None));
pub fn get_timestamp<'a>(
&'a self,
key: &str
) -> RawResult<Option<RawBsonTimestamp<'a>>>
[src]
&'a self,
key: &str
) -> RawResult<Option<RawBsonTimestamp<'a>>>
Get an element from the document, and convert it to a timestamp.
Returns an error if the document is malformed, or if the retrieved value
is not an i32. Returns Ok(None)
if the key is not found in the document.
use bson::{doc, Timestamp}; let docbuf = DocBuf::from_document(&doc! { "bool": true, "ts": Timestamp { time: 649876543, increment: 9 }, }); let timestamp = docbuf.get_timestamp("ts")?.unwrap(); assert_eq!(timestamp.time(), 649876543); assert_eq!(timestamp.increment(), 9); assert_eq!(docbuf.get_timestamp("bool"), Err(RawError::UnexpectedType)); assert_eq!(docbuf.get_timestamp("unknown"), Ok(None));
pub fn get_i64(&self, key: &str) -> RawResult<Option<i64>>
[src]
Get an element from the document, and convert it to i64.
Returns an error if the document is malformed, or if the retrieved value
is not an i64. Returns Ok(None)
if the key is not found in the document.
use bson::doc; let docbuf = DocBuf::from_document(&doc! { "bool": true, "i64": 9223372036854775807_i64, }); assert_eq!(docbuf.get_i64("i64"), Ok(Some(9223372036854775807))); assert_eq!(docbuf.get_i64("bool"), Err(RawError::UnexpectedType)); assert_eq!(docbuf.get_i64("unknown"), Ok(None));
pub fn as_bytes(&self) -> &[u8]
[src]
Return a reference to the contained data as a &[u8]
use bson::doc; let docbuf = DocBuf::from_document(&doc!{}); assert_eq!(docbuf.as_bytes(), b"\x05\x00\x00\x00\x00");
Trait Implementations
impl AsRef<Doc> for DocBuf
[src]
impl Borrow<Doc> for DocBuf
[src]
impl Clone for DocBuf
[src]
impl Debug for DocBuf
[src]
impl Deref for DocBuf
[src]
impl<'a> IntoIterator for &'a DocBuf
[src]
Auto Trait Implementations
impl RefUnwindSafe for DocBuf
[src]
impl Send for DocBuf
[src]
impl Sync for DocBuf
[src]
impl Unpin for DocBuf
[src]
impl UnwindSafe for DocBuf
[src]
Blanket Implementations
impl<T> Any for T where
T: 'static + ?Sized,
[src]
T: 'static + ?Sized,
impl<T> Borrow<T> for T where
T: ?Sized,
[src]
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]
T: ?Sized,
pub fn borrow_mut(&mut self) -> &mut T
[src]
impl<T> From<T> for T
[src]
impl<T, U> Into<U> for T where
U: From<T>,
[src]
U: From<T>,
impl<T> ToOwned for T where
T: Clone,
[src]
T: Clone,
type Owned = T
The resulting type after obtaining ownership.
pub fn to_owned(&self) -> T
[src]
pub fn clone_into(&self, target: &mut T)
[src]
impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]
U: Into<T>,
type Error = Infallible
The type returned in the event of a conversion error.
pub fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]
impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]
U: TryFrom<T>,
type Error = <U as TryFrom<T>>::Error
The type returned in the event of a conversion error.
pub fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
[src]
impl<V, T> VZip<V> for T where
V: MultiLane<T>,
V: MultiLane<T>,