Skip to content

Commit a25bf3c

Browse files
authored
RUST-1119 Add bson::to_raw_document_buf function (#330)
1 parent 7983b63 commit a25bf3c

File tree

2 files changed

+29
-3
lines changed

2 files changed

+29
-3
lines changed

src/lib.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -278,12 +278,12 @@ pub use self::{
278278
},
279279
decimal128::Decimal128,
280280
raw::{
281-
RawBson, RawArray, RawArrayBuf, RawBinaryRef, RawBsonRef, RawDbPointerRef, RawDocument,
281+
RawArray, RawArrayBuf, RawBinaryRef, RawBson, RawBsonRef, RawDbPointerRef, RawDocument,
282282
RawDocumentBuf, RawJavaScriptCodeWithScopeRef, RawRegexRef,
283283
},
284284
ser::{
285-
to_bson, to_bson_with_options, to_document, to_document_with_options, to_vec, Serializer,
286-
SerializerOptions,
285+
to_bson, to_bson_with_options, to_document, to_document_with_options, to_raw_document_buf,
286+
to_vec, Serializer, SerializerOptions,
287287
},
288288
uuid::{Uuid, UuidRepresentation},
289289
};

src/ser/mod.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ use crate::{
3737
de::MAX_BSON_SIZE,
3838
spec::BinarySubtype,
3939
Binary,
40+
RawDocumentBuf,
4041
};
4142
use ::serde::{ser::Error as SerdeError, Serialize};
4243

@@ -283,3 +284,28 @@ where
283284
value.serialize(&mut serializer)?;
284285
Ok(serializer.into_vec())
285286
}
287+
288+
/// Serialize the given `T` as a [`RawDocumentBuf`].
289+
///
290+
/// ```rust
291+
/// use serde::Serialize;
292+
/// use bson::rawdoc;
293+
///
294+
/// #[derive(Serialize)]
295+
/// struct Cat {
296+
/// name: String,
297+
/// age: i32
298+
/// }
299+
///
300+
/// let cat = Cat { name: "Garfield".to_string(), age: 43 };
301+
/// let doc = bson::to_raw_document_buf(&cat)?;
302+
/// assert_eq!(doc, rawdoc! { "name": "Garfield", "age": 43 });
303+
/// # Ok::<(), Box<dyn std::error::Error>>(())
304+
/// ```
305+
#[inline]
306+
pub fn to_raw_document_buf<T>(value: &T) -> Result<RawDocumentBuf>
307+
where
308+
T: Serialize,
309+
{
310+
RawDocumentBuf::from_bytes(to_vec(value)?).map_err(Error::custom)
311+
}

0 commit comments

Comments
 (0)