| 1 |
// The MIT License (MIT) |
| 2 |
|
| 3 |
// Copyright (c) 2015 Y. T. Chung <[email protected]> |
| 4 |
|
| 5 |
// Permission is hereby granted, free of charge, to any person obtaining a copy of |
| 6 |
// this software and associated documentation files (the "Software"), to deal in |
| 7 |
// the Software without restriction, including without limitation the rights to |
| 8 |
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of |
| 9 |
// the Software, and to permit persons to whom the Software is furnished to do so, |
| 10 |
// subject to the following conditions: |
| 11 |
|
| 12 |
// The above copyright notice and this permission notice shall be included in all |
| 13 |
// copies or substantial portions of the Software. |
| 14 |
|
| 15 |
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 16 |
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS |
| 17 |
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR |
| 18 |
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER |
| 19 |
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN |
| 20 |
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 21 |
|
| 22 |
//! Serializer |
| 23 |
|
| 24 |
mod error; |
| 25 |
mod raw; |
| 26 |
mod serde; |
| 27 |
|
| 28 |
pub use self::{ |
| 29 |
error::{Error, Result}, |
| 30 |
serde::{Serializer, SerializerOptions}, |
| 31 |
}; |
| 32 |
|
| 33 |
use std::io::Write; |
| 34 |
|
| 35 |
use crate::{ |
| 36 |
bson::{Bson, Document}, |
| 37 |
de::MAX_BSON_SIZE, |
| 38 |
spec::BinarySubtype, |
| 39 |
RawDocumentBuf, |
| 40 |
}; |
| 41 |
use ::serde::{ser::Error as SerdeError, Serialize}; |
| 42 |
|
| 43 |
fn write_string<W: Write + ?Sized>(writer: &mut W, s: &str) -> Result<()> { |
| 44 |
writer.write_all(&(s.len() as i32 + 1).to_le_bytes())?; |
| 45 |
writer.write_all(s.as_bytes())?; |
| 46 |
writer.write_all(b"\0")?; |
| 47 |
Ok(()) |
| 48 |
} |
| 49 |
|
| 50 |
fn write_cstring<W: Write + ?Sized>(writer: &mut W, s: &str) -> Result<()> { |
| 51 |
if s.contains('\0') { |
| 52 |
return Err(Error::InvalidCString(s.into())); |
| 53 |
} |
| 54 |
writer.write_all(s.as_bytes())?; |
| 55 |
writer.write_all(b"\0")?; |
| 56 |
Ok(()) |
| 57 |
} |
| 58 |
|
| 59 |
#[inline] |
| 60 |
pub(crate) fn write_i32<W: Write + ?Sized>(writer: &mut W, val: i32) -> Result<()> { |
| 61 |
writer |
| 62 |
.write_all(&val.to_le_bytes()) |
| 63 |
.map(|_| ()) |
| 64 |
.map_err(From::from) |
| 65 |
} |
| 66 |
|
| 67 |
#[inline] |
| 68 |
fn write_i64<W: Write + ?Sized>(writer: &mut W, val: i64) -> Result<()> { |
| 69 |
writer |
| 70 |
.write_all(&val.to_le_bytes()) |
| 71 |
.map(|_| ()) |
| 72 |
.map_err(From::from) |
| 73 |
} |
| 74 |
|
| 75 |
#[inline] |
| 76 |
fn write_f64<W: Write + ?Sized>(writer: &mut W, val: f64) -> Result<()> { |
| 77 |
writer |
| 78 |
.write_all(&val.to_le_bytes()) |
| 79 |
.map(|_| ()) |
| 80 |
.map_err(From::from) |
| 81 |
} |
| 82 |
|
| 83 |
#[inline] |
| 84 |
fn write_binary<W: Write>(mut writer: W, bytes: &[u8], subtype: BinarySubtype) -> Result<()> { |
| 85 |
let len = if let BinarySubtype::BinaryOld = subtype { |
| 86 |
bytes.len() + 4 |
| 87 |
} else { |
| 88 |
bytes.len() |
| 89 |
}; |
| 90 |
|
| 91 |
if len > MAX_BSON_SIZE as usize { |
| 92 |
return Err(Error::custom(format!( |
| 93 |
"binary length {} exceeded maximum size", |
| 94 |
bytes.len() |
| 95 |
))); |
| 96 |
} |
| 97 |
|
| 98 |
write_i32(&mut writer, len as i32)?; |
| 99 |
writer.write_all(&[subtype.into()])?; |
| 100 |
|
| 101 |
if let BinarySubtype::BinaryOld = subtype { |
| 102 |
write_i32(&mut writer, len as i32 - 4)?; |
| 103 |
}; |
| 104 |
|
| 105 |
writer.write_all(bytes).map_err(From::from) |
| 106 |
} |
| 107 |
|
| 108 |
/// Encode a `T` Serializable into a [`Bson`] value. |
| 109 |
/// |
| 110 |
/// The [`Serializer`] used by this function presents itself as human readable, whereas the |
| 111 |
/// one used in [`to_vec`] does not. This means that this function will produce different BSON than |
| 112 |
/// [`to_vec`] for types that change their serialization output depending on whether |
| 113 |
/// the format is human readable or not. To serialize to a [`Document`] with a serializer that |
| 114 |
/// presents itself as not human readable, use [`to_bson_with_options`] with |
| 115 |
/// [`SerializerOptions::human_readable`] set to false. |
| 116 |
pub fn to_bson<T: ?Sized>(value: &T) -> Result<Bson> |
| 117 |
where |
| 118 |
T: Serialize, |
| 119 |
{ |
| 120 |
let ser = Serializer::new(); |
| 121 |
value.serialize(ser) |
| 122 |
} |
| 123 |
|
| 124 |
/// Encode a `T` into a [`Bson`] value, configuring the underlying serializer with the provided |
| 125 |
/// options. |
| 126 |
/// ``` |
| 127 |
/// # use serde::Serialize; |
| 128 |
/// # use bson::{bson, SerializerOptions}; |
| 129 |
/// #[derive(Debug, Serialize)] |
| 130 |
/// struct MyData { |
| 131 |
/// a: String, |
| 132 |
/// } |
| 133 |
/// |
| 134 |
/// let data = MyData { a: "ok".to_string() }; |
| 135 |
/// let options = SerializerOptions::builder().human_readable(false).build(); |
| 136 |
/// let bson = bson::to_bson_with_options(&data, options)?; |
| 137 |
/// assert_eq!(bson, bson!({ "a": "ok" })); |
| 138 |
/// # Ok::<(), Box<dyn std::error::Error>>(()) |
| 139 |
/// ``` |
| 140 |
pub fn to_bson_with_options<T: ?Sized>(value: &T, options: SerializerOptions) -> Result<Bson> |
| 141 |
where |
| 142 |
T: Serialize, |
| 143 |
{ |
| 144 |
let ser = Serializer::new_with_options(options); |
| 145 |
value.serialize(ser) |
| 146 |
} |
| 147 |
|
| 148 |
/// Encode a `T` Serializable into a BSON [`Document`]. |
| 149 |
/// |
| 150 |
/// The [`Serializer`] used by this function presents itself as human readable, whereas the |
| 151 |
/// one used in [`to_vec`] does not. This means that this function will produce different BSON than |
| 152 |
/// [`to_vec`] for types that change their serialization output depending on whether |
| 153 |
/// the format is human readable or not. To serialize to a [`Document`] with a serializer that |
| 154 |
/// presents itself as not human readable, use [`to_document_with_options`] with |
| 155 |
/// [`SerializerOptions::human_readable`] set to false. |
| 156 |
pub fn to_document<T: ?Sized>(value: &T) -> Result<Document> |
| 157 |
where |
| 158 |
T: Serialize, |
| 159 |
{ |
| 160 |
to_document_with_options(value, Default::default()) |
| 161 |
} |
| 162 |
|
| 163 |
/// Encode a `T` into a [`Document`], configuring the underlying serializer with the provided |
| 164 |
/// options. |
| 165 |
/// ``` |
| 166 |
/// # use serde::Serialize; |
| 167 |
/// # use bson::{doc, SerializerOptions}; |
| 168 |
/// #[derive(Debug, Serialize)] |
| 169 |
/// struct MyData { |
| 170 |
/// a: String, |
| 171 |
/// } |
| 172 |
/// |
| 173 |
/// let data = MyData { a: "ok".to_string() }; |
| 174 |
/// let options = SerializerOptions::builder().human_readable(false).build(); |
| 175 |
/// let doc = bson::to_document_with_options(&data, options)?; |
| 176 |
/// assert_eq!(doc, doc! { "a": "ok" }); |
| 177 |
/// # Ok::<(), Box<dyn std::error::Error>>(()) |
| 178 |
/// ``` |
| 179 |
pub fn to_document_with_options<T: ?Sized>( |
| 180 |
value: &T, |
| 181 |
options: SerializerOptions, |
| 182 |
) -> Result<Document> |
| 183 |
where |
| 184 |
T: Serialize, |
| 185 |
{ |
| 186 |
match to_bson_with_options(value, options)? { |
| 187 |
Bson::Document(doc) => Ok(doc), |
| 188 |
bson => Err(Error::SerializationError { |
| 189 |
message: format!( |
| 190 |
"Could not be serialized to Document, got {:?} instead", |
| 191 |
bson.element_type() |
| 192 |
), |
| 193 |
}), |
| 194 |
} |
| 195 |
} |
| 196 |
|
| 197 |
/// Serialize the given `T` as a BSON byte vector. |
| 198 |
#[inline] |
| 199 |
pub fn to_vec<T>(value: &T) -> Result<Vec<u8>> |
| 200 |
where |
| 201 |
T: Serialize, |
| 202 |
{ |
| 203 |
let mut serializer = raw::Serializer::new(); |
| 204 |
value.serialize(&mut serializer)?; |
| 205 |
Ok(serializer.into_vec()) |
| 206 |
} |
| 207 |
|
| 208 |
/// Serialize the given `T` as a [`RawDocumentBuf`]. |
| 209 |
/// |
| 210 |
/// ```rust |
| 211 |
/// use serde::Serialize; |
| 212 |
/// use bson::rawdoc; |
| 213 |
/// |
| 214 |
/// #[derive(Serialize)] |
| 215 |
/// struct Cat { |
| 216 |
/// name: String, |
| 217 |
/// age: i32 |
| 218 |
/// } |
| 219 |
/// |
| 220 |
/// let cat = Cat { name: "Garfield".to_string(), age: 43 }; |
| 221 |
/// let doc = bson::to_raw_document_buf(&cat)?; |
| 222 |
/// assert_eq!(doc, rawdoc! { "name": "Garfield", "age": 43 }); |
| 223 |
/// # Ok::<(), Box<dyn std::error::Error>>(()) |
| 224 |
/// ``` |
| 225 |
#[inline] |
| 226 |
pub fn to_raw_document_buf<T>(value: &T) -> Result<RawDocumentBuf> |
| 227 |
where |
| 228 |
T: Serialize, |
| 229 |
{ |
| 230 |
RawDocumentBuf::from_bytes(to_vec(value)?).map_err(Error::custom) |
| 231 |
} |