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
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
impl Doc
pub fn new<D: AsRef<[u8]> + ?Sized>(data: &D) -> RawResult<&Doc>
Sourcepub unsafe fn new_unchecked<D: AsRef<[u8]> + ?Sized>(data: &D) -> &Doc
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") };Sourcepub fn to_docbuf(&self) -> DocBuf
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();Sourcepub fn get<'a>(&'a self, key: &str) -> RawResult<Option<Element<'a>>>
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());Sourcepub fn get_f64(&self, key: &str) -> RawResult<Option<f64>>
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));Sourcepub fn get_str<'a>(&'a self, key: &str) -> RawResult<Option<&'a str>>
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));Sourcepub fn get_document<'a>(&'a self, key: &str) -> RawResult<Option<&'a Doc>>
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());Sourcepub fn get_array<'a>(&'a self, key: &str) -> RawResult<Option<&'a Array>>
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());Sourcepub fn get_binary<'a>(
&'a self,
key: &str,
) -> RawResult<Option<RawBsonBinary<'a>>>
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());Sourcepub fn get_object_id(&self, key: &str) -> RawResult<Option<ObjectId>>
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());Sourcepub fn get_bool(&self, key: &str) -> RawResult<Option<bool>>
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());Sourcepub fn get_datetime(&self, key: &str) -> RawResult<Option<DateTime<Utc>>>
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());Sourcepub fn get_null(&self, key: &str) -> RawResult<Option<()>>
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());Sourcepub fn get_regex<'a>(&'a self, key: &str) -> RawResult<Option<RawBsonRegex<'a>>>
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());Sourcepub fn get_javascript<'a>(&'a self, key: &str) -> RawResult<Option<&'a str>>
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());Sourcepub fn get_symbol<'a>(&'a self, key: &str) -> RawResult<Option<&'a str>>
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());Sourcepub fn get_javascript_with_scope<'a>(
&'a self,
key: &str,
) -> RawResult<Option<(&'a str, &'a Doc)>>
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());Sourcepub fn get_i32(&self, key: &str) -> RawResult<Option<i32>>
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));Sourcepub fn get_timestamp<'a>(
&'a self,
key: &str,
) -> RawResult<Option<RawBsonTimestamp<'a>>>
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));Sourcepub fn get_i64(&self, key: &str) -> RawResult<Option<i64>>
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));