mod raw;
mod serde;
pub use self::serde::Serializer;
#[rustfmt::skip]
use ::serde::{ser::Error as SerdeError, Serialize};
use crate::{
bson::{Bson, Document},
error::{Error, Result},
ser::serde::SerializerOptions,
RawDocumentBuf,
};
pub fn serialize_to_bson<T>(value: &T) -> Result<Bson>
where
T: Serialize + ?Sized,
{
let ser = Serializer::new();
#[cfg(feature = "serde_path_to_error")]
{
serde_path_to_error::serialize(value, ser).map_err(Error::with_path)
}
#[cfg(not(feature = "serde_path_to_error"))]
value.serialize(ser)
}
pub(crate) fn to_bson_with_options<T>(value: &T, options: SerializerOptions) -> Result<Bson>
where
T: Serialize + ?Sized,
{
let ser = Serializer::new_with_options(options);
value.serialize(ser)
}
pub fn serialize_to_document<T>(value: &T) -> Result<Document>
where
T: Serialize + ?Sized,
{
match serialize_to_bson(value)? {
Bson::Document(doc) => Ok(doc),
bson => Err(Error::serialization(format!(
"expected to serialize document, got type {:?} instead",
bson.element_type()
))),
}
}
#[inline]
pub fn serialize_to_vec<T>(value: &T) -> Result<Vec<u8>>
where
T: Serialize,
{
let mut bytes = Vec::new();
serialize_to_buffer(value, &mut bytes)?;
Ok(bytes)
}
#[inline]
pub fn serialize_to_buffer<T>(value: &T, buffer: &mut Vec<u8>) -> Result<()>
where
T: Serialize,
{
let mut serializer = raw::Serializer::new(buffer);
#[cfg(feature = "serde_path_to_error")]
{
serde_path_to_error::serialize(value, &mut serializer).map_err(Error::with_path)?;
}
#[cfg(not(feature = "serde_path_to_error"))]
{
value.serialize(&mut serializer)?;
}
Ok(())
}
#[inline]
pub fn serialize_to_raw_document_buf<T>(value: &T) -> Result<RawDocumentBuf>
where
T: Serialize,
{
RawDocumentBuf::from_bytes(serialize_to_vec(value)?).map_err(Error::custom)
}