From f9f5f70d1e2141d3bf619ec8da8a5ed4a35b8fe3 Mon Sep 17 00:00:00 2001 From: Patrick Freed Date: Wed, 1 Dec 2021 18:58:55 -0500 Subject: [PATCH 1/2] add `bson::to_raw_document_buf` function --- src/lib.rs | 6 +++--- src/ser/mod.rs | 25 +++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) 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..482507c0 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,27 @@ where value.serialize(&mut serializer)?; Ok(serializer.into_vec()) } + +/// Serialize the given `T` as a [`RawDocumentBuf`]. +/// +/// ```rust +/// use serde::Serialize; +/// +/// #[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) +} From 8307afa6db231e62af212e19f814140af6bf5278 Mon Sep 17 00:00:00 2001 From: Patrick Freed Date: Fri, 3 Dec 2021 13:22:14 -0500 Subject: [PATCH 2/2] uncomment line in example --- src/ser/mod.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/ser/mod.rs b/src/ser/mod.rs index 482507c0..fd2c34f9 100644 --- a/src/ser/mod.rs +++ b/src/ser/mod.rs @@ -289,6 +289,7 @@ where /// /// ```rust /// use serde::Serialize; +/// use bson::rawdoc; /// /// #[derive(Serialize)] /// struct Cat { @@ -298,7 +299,7 @@ where /// /// 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 }) +/// assert_eq!(doc, rawdoc! { "name": "Garfield", "age": 43 }); /// # Ok::<(), Box>(()) /// ``` #[inline]