Struct Doc

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

A BSON document, referencing raw binary data stored elsewhere. This can be created from a DocBuf or any type that contains valid BSON data, and can be referenced as a [u8], including static binary literals, Vec, or arrays.

Accessing elements within the Doc 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.

Doc can be iterated over, yielding a Result containing key-value pairs that share the borrow with the source bytes instead of allocating, when necessary.

let doc = Doc::new(b"\x13\x00\x00\x00\x02hi\x00\x06\x00\x00\x00y'all\x00\x00")?;
let mut iter = doc.into_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 doc.get(&key), or any of the get_* methods, like doc.get_object_id(&key), and doc.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 Doc

Source

pub fn new<D: AsRef<[u8]> + ?Sized>(data: &D) -> RawResult<&Doc>

Source

pub unsafe fn new_unchecked<D: AsRef<[u8]> + ?Sized>(data: &D) -> &Doc

Create a new Doc referencing the provided data slice.

§Safety

The provided data must begin with a valid size and end with a NUL-terminator.

let doc: &Doc = unsafe { Doc::new_unchecked(b"\x05\0\0\0\0") };
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 Doc

Source§

fn as_ref(&self) -> &Doc

Converts this type into a shared reference of the (usually inferred) input type.
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 Debug for Doc

Source§

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

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

impl<'a> IntoIterator for &'a Doc

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 ToOwned for Doc

Source§

type Owned = DocBuf

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> Self::Owned

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

fn clone_into(&self, target: &mut Self::Owned)

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

impl TryFrom<&Doc> for Document

Source§

type Error = RawError

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

fn try_from(rawdoc: &Doc) -> RawResult<Document>

Performs the conversion.

Auto Trait Implementations§

§

impl Freeze for Doc

§

impl RefUnwindSafe for Doc

§

impl Send for Doc

§

impl !Sized for Doc

§

impl Sync for Doc

§

impl Unpin for Doc

§

impl UnwindSafe for Doc

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