diff --git a/src/lib.rs b/src/lib.rs index 8d309e4f..8ac4ee37 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -278,12 +278,12 @@ pub use self::{ }, decimal128::Decimal128, raw::{ - RawBson, RawArray, RawArrayBuf, RawBinaryRef, RawBsonRef, RawDbPointerRef, RawDocument, + RawArray, RawArrayBuf, RawBinaryRef, RawBson, RawBsonRef, RawDbPointerRef, RawDocument, RawDocumentBuf, RawJavaScriptCodeWithScopeRef, RawRegexRef, }, ser::{ - to_bson, to_bson_with_options, to_document, to_document_with_options, to_vec, Serializer, - SerializerOptions, + to_bson, to_bson_with_options, to_document, to_document_with_options, to_raw_document_buf, + to_vec, Serializer, SerializerOptions, }, uuid::{Uuid, UuidRepresentation}, }; diff --git a/src/ser/mod.rs b/src/ser/mod.rs index e133d952..fd2c34f9 100644 --- a/src/ser/mod.rs +++ b/src/ser/mod.rs @@ -37,6 +37,7 @@ use crate::{ de::MAX_BSON_SIZE, spec::BinarySubtype, Binary, + RawDocumentBuf, }; use ::serde::{ser::Error as SerdeError, Serialize}; @@ -283,3 +284,28 @@ where value.serialize(&mut serializer)?; Ok(serializer.into_vec()) } + +/// Serialize the given `T` as a [`RawDocumentBuf`]. +/// +/// ```rust +/// use serde::Serialize; +/// use bson::rawdoc; +/// +/// #[derive(Serialize)] +/// struct Cat { +/// name: String, +/// age: i32 +/// } +/// +/// let cat = Cat { name: "Garfield".to_string(), age: 43 }; +/// let doc = bson::to_raw_document_buf(&cat)?; +/// assert_eq!(doc, rawdoc! { "name": "Garfield", "age": 43 }); +/// # Ok::<(), Box>(()) +/// ``` +#[inline] +pub fn to_raw_document_buf(value: &T) -> Result +where + T: Serialize, +{ + RawDocumentBuf::from_bytes(to_vec(value)?).map_err(Error::custom) +}