[go: up one dir, main page]

Module raw

Module raw 

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

BindValue
A struct to use as the Target of a BindRawBsonRef impl 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 a str via TryFrom.
CString
An owned BSON-spec cstring: Zero or more UTF-8 encoded characters, excluding the nul byte. CString is to CStr as String is to str. Can be constructed from a CStr via ToOwned/Into or from a String or str via TryFrom.
RawArray
A slice of a BSON document containing a BSON array value (akin to std::str). This can be retrieved from a RawDocument via RawDocument::get.
RawArrayBuf
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 to RawDocumentBuf or as a field in a Deserialize struct.
RawArrayIter
An iterator over borrowed raw BSON array values.
RawBinaryRef
A BSON binary value referencing raw bytes stored elsewhere.
RawDbPointerRef
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 a RawDocumentBuf or any type that contains valid BSON data, including static binary literals, Vec<u8>, or arrays.
RawDocumentBuf
An owned BSON document (akin to std::path::PathBuf), backed by a buffer of raw BSON bytes. This can be created from a Vec<u8> or a crate::Document.
RawElement
A view into a value contained in a RawDocument or RawDocumentBuf. The underlying bytes of the element are not parsed or validated; call RawElement::value or one of the TryFrom implementations to convert the element into a BSON value.
RawIter
An iterator over the document’s elements.
RawJavaScriptCodeWithScope
A BSON “code with scope” value backed by owned raw BSON.
RawJavaScriptCodeWithScopeRef
A BSON “code with scope” value referencing raw bytes stored elsewhere.
RawRegexRef
A BSON regex referencing raw bytes stored elsewhere.

Enums§

RawBson
A BSON value backed by owned raw BSON bytes.
RawBsonRef
A BSON value referencing raw bytes stored elsewhere.

Traits§

BindRawBsonRef
Types that can be consumed to produce raw bson references valid for a limited lifetime. Conceptually a union between T: Into<RawBson> and T: Into<RawBsonRef>; if your type implements Into<RawBsonRef> it will automatically implement this, but if it implements Into<RawBson> it will need to also define an impl of BindRawBsonRef: