Struct DocBuf

Source
pub struct DocBuf { /* private fields */ }
Expand description

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§

Source§

impl DocBuf

Source

pub fn new(data: Vec<u8>) -> RawResult<DocBuf>

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())?;
Source

pub fn from_document(doc: &Document) -> DocBuf

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);
Source

pub unsafe fn new_unchecked(data: Vec<u8>) -> DocBuf

Create a DocBuf from an owned Vec without performing any checks on the provided data.

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.

Source

pub fn as_docref(&self) -> &Doc

👎Deprecated since 0.2.0: 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();
Source

pub fn iter(&self) -> DocIter<'_>

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.

Source

pub fn into_inner(self) -> Vec<u8>

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>§

Source

pub fn to_docbuf(&self) -> DocBuf

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 = doc.to_docbuf();
Source

pub fn get<'a>(&'a self, key: &str) -> RawResult<Option<Element<'a>>>

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());
Source

pub fn get_f64(&self, key: &str) -> RawResult<Option<f64>>

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));
Source

pub fn get_str<'a>(&'a self, key: &str) -> RawResult<Option<&'a str>>

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));
Source

pub fn get_document<'a>(&'a self, key: &str) -> RawResult<Option<&'a Doc>>

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());
Source

pub fn get_array<'a>(&'a self, key: &str) -> RawResult<Option<&'a Array>>

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());
Source

pub fn get_binary<'a>( &'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());
Source

pub fn get_object_id(&self, key: &str) -> RawResult<Option<ObjectId>>

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());
Source

pub fn get_bool(&self, key: &str) -> RawResult<Option<bool>>

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());
Source

pub fn get_datetime(&self, key: &str) -> RawResult<Option<DateTime<Utc>>>

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());
Source

pub fn get_null(&self, key: &str) -> RawResult<Option<()>>

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());
Source

pub fn get_regex<'a>(&'a self, key: &str) -> RawResult<Option<RawBsonRegex<'a>>>

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());
Source

pub fn get_javascript<'a>(&'a self, key: &str) -> RawResult<Option<&'a str>>

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());
Source

pub fn get_symbol<'a>(&'a self, key: &str) -> RawResult<Option<&'a str>>

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());
Source

pub fn get_javascript_with_scope<'a>( &'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());
Source

pub fn get_i32(&self, key: &str) -> RawResult<Option<i32>>

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));
Source

pub fn get_timestamp<'a>( &'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));
Source

pub fn get_i64(&self, key: &str) -> RawResult<Option<i64>>

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));
Source

pub fn as_bytes(&self) -> &[u8]

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§

Source§

impl AsRef<Doc> for DocBuf

Source§

fn as_ref(&self) -> &Doc

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl Borrow<Doc> for DocBuf

Source§

fn borrow(&self) -> &Doc

Immutably borrows from an owned value. Read more
Source§

impl Clone for DocBuf

Source§

fn clone(&self) -> DocBuf

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DocBuf

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Deref for DocBuf

Source§

type Target = Doc

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl<'a> IntoIterator for &'a DocBuf

Source§

type IntoIter = DocIter<'a>

Which kind of iterator are we turning this into?
Source§

type Item = Result<(&'a str, Element<'a>), RawError>

The type of the elements being iterated over.
Source§

fn into_iter(self) -> DocIter<'a>

Creates an iterator from a value. Read more
Source§

impl TryFrom<DocBuf> for Document

Source§

type Error = RawError

The type returned in the event of a conversion error.
Source§

fn try_from(rawdoc: DocBuf) -> RawResult<Document>

Performs the conversion.

Auto Trait Implementations§

§

impl Freeze for DocBuf

§

impl RefUnwindSafe for DocBuf

§

impl Send for DocBuf

§

impl Sync for DocBuf

§

impl Unpin for DocBuf

§

impl UnwindSafe for DocBuf

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V