Expand description
An API for interacting with raw BSON bytes.
This module provides two document types, RawDocumentBuf and &RawDocument
(an owned buffer and a reference respectively, akin to String and &str), for
working with raw BSON documents. These types differ from the regular
Document type in that their storage is BSON bytes rather than a hash-map
like Rust type. In certain circumstances, these types can be leveraged for increased
performance.
This module also provides a RawBson type for modeling any borrowed BSON element and a
RawArray type for modeling a borrowed slice of a document containing a BSON array element.
A RawDocumentBuf can be created from a Vec<u8> containing raw BSON data. A
&RawDocument can be created from anything that can be borrowed as a &[u8].
Both types can access elements via methods similar to those available on the
Document type. Note that RawDocument::get (which RawDocumentBuf
calls through to via its Deref implementation) returns a Result, since
the bytes contained in the document are not fully validated until trying to access the contained
data.
use bson::raw::{
RawBson,
RawDocumentBuf,
};
// See http://bsonspec.org/spec.html for details on the binary encoding of BSON.
let doc = RawDocumentBuf::from_bytes(b"\x13\x00\x00\x00\x02hi\x00\x06\x00\x00\x00y'all\x00\x00".to_vec())?;
let elem = doc.get("hi")?.unwrap();
assert_eq!(
elem.as_str(),
Some("y'all"),
);§Document interop
A RawDocumentBuf can be created from a Document via its TryFrom
impl. This encodes the Document as a byte buffer, and then returns those bytes as a
RawDocumentBuf; this will fail if the Document contains values not allowed in encoded BSON
(such as embedded nul bytes in string keys).
use bson::{
raw::RawDocumentBuf,
doc,
};
let document = doc! {
"goodbye": {
"cruel": "world"
}
};
let raw = RawDocumentBuf::try_from(&document)?;
let value = raw
.get_document("goodbye")?
.get_str("cruel")?;
assert_eq!(
value,
"world",
);Conversion in the other direction, from &RawDocument to
Document, can also be done via TryFrom. This will fail if the byte
buffer in the &RawDocument contains invalid BSON.
RawBson and RawArrayBuf can similary be constructed from their equivalent base crate
types, and their corresponding reference types can be converted to the base crate types.
§Reference type (RawDocument)
A BSON document can also be accessed with the RawDocument type, which is an
unsized type that represents the BSON payload as a [u8]. This allows accessing nested
documents without reallocation. RawDocument must always be accessed via a pointer type,
similar to [T] and str.
The below example constructs a bson document in a stack-based array,
and extracts a &str from it, performing no heap allocation.
use bson::raw::RawDocument;
let bytes = b"\x13\x00\x00\x00\x02hi\x00\x06\x00\x00\x00y'all\x00\x00";
assert_eq!(RawDocument::from_bytes(bytes)?.get_str("hi")?, "y'all");§Iteration
RawDocument implements IntoIterator, which can also be
accessed via RawDocumentBuf::iter.
use bson::{
raw::{
cstr,
CStr,
RawBsonRef,
RawDocumentBuf,
},
doc,
};
let original_doc = doc! {
"crate": "bson",
"year": "2021",
};
let doc = RawDocumentBuf::try_from(&original_doc)?;
let mut doc_iter = doc.iter();
let (key, value): (&CStr, RawBsonRef) = doc_iter.next().unwrap()?;
assert_eq!(key, cstr!("crate"));
assert_eq!(value.as_str(), Some("bson"));
let (key, value): (&CStr, RawBsonRef) = doc_iter.next().unwrap()?;
assert_eq!(key, cstr!("year"));
assert_eq!(value.as_str(), Some("2021"));Macros§
- cstr
- Construct a
'static &CStr. The validitiy will be verified at compile-time.
Structs§
- Bind
Value - A struct to use as the
Targetof aBindRawBsonRefimpl for custom types. - CStr
- A borrowed BSON-spec cstring: Zero or more UTF-8 encoded characters, excluding the nul byte.
Can be constructed at compile-time via the
cstr!macro or at run-time from astrviaTryFrom. - CString
- An owned BSON-spec cstring: Zero or more UTF-8 encoded characters, excluding the nul byte.
CStringis toCStrasStringis tostr. Can be constructed from aCStrviaToOwned/Intoor from aStringorstrviaTryFrom. - RawArray
- A slice of a BSON document containing a BSON array value (akin to
std::str). This can be retrieved from aRawDocumentviaRawDocument::get. - RawArray
Buf - An owned BSON array value (akin to
std::path::PathBuf), backed by a buffer of raw BSON bytes. This type can be used to construct owned array values, which can be used to append toRawDocumentBufor as a field in aDeserializestruct. - RawArray
Iter - An iterator over borrowed raw BSON array values.
- RawBinary
Ref - A BSON binary value referencing raw bytes stored elsewhere.
- RawDb
Pointer Ref - A BSON DB pointer value referencing raw bytes stored elesewhere.
- RawDocument
- A slice of a BSON document (akin to
std::str). This can be created from aRawDocumentBufor any type that contains valid BSON data, including static binary literals,Vec<u8>, or arrays. - RawDocument
Buf - An owned BSON document (akin to
std::path::PathBuf), backed by a buffer of raw BSON bytes. This can be created from aVec<u8>or acrate::Document. - RawElement
- A view into a value contained in a
RawDocumentorRawDocumentBuf. The underlying bytes of the element are not parsed or validated; callRawElement::valueor one of theTryFromimplementations to convert the element into a BSON value. - RawIter
- An iterator over the document’s elements.
- RawJava
Script Code With Scope - A BSON “code with scope” value backed by owned raw BSON.
- RawJava
Script Code With Scope Ref - A BSON “code with scope” value referencing raw bytes stored elsewhere.
- RawRegex
Ref - A BSON regex referencing raw bytes stored elsewhere.
Enums§
- RawBson
- A BSON value backed by owned raw BSON bytes.
- RawBson
Ref - A BSON value referencing raw bytes stored elsewhere.
Traits§
- Bind
RawBson Ref - Types that can be consumed to produce raw bson references valid for a limited lifetime.
Conceptually a union between
T: Into<RawBson>andT: Into<RawBsonRef>; if your type implementsInto<RawBsonRef>it will automatically implement this, but if it implementsInto<RawBson>it will need to also define an impl ofBindRawBsonRef: