| 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 |
//! Deserializer |
| 23 |
|
| 24 |
mod error; |
| 25 |
mod raw; |
| 26 |
mod serde; |
| 27 |
|
| 28 |
pub use self::{ |
| 29 |
error::{Error, Result}, |
| 30 |
serde::{Deserializer, DeserializerOptions}, |
| 31 |
}; |
| 32 |
|
| 33 |
use std::io::Read; |
| 34 |
|
| 35 |
use crate::{ |
| 36 |
bson::{Bson, Document, Timestamp}, |
| 37 |
oid::ObjectId, |
| 38 |
raw::RawBinaryRef, |
| 39 |
ser::write_i32, |
| 40 |
spec::BinarySubtype, |
| 41 |
Decimal128, |
| 42 |
}; |
| 43 |
|
| 44 |
use ::serde::{ |
| 45 |
de::{DeserializeOwned, Error as _, Unexpected}, |
| 46 |
Deserialize, |
| 47 |
}; |
| 48 |
|
| 49 |
pub(crate) use self::serde::{convert_unsigned_to_signed_raw, BsonVisitor}; |
| 50 |
|
| 51 |
pub(crate) use self::raw::Deserializer as RawDeserializer; |
| 52 |
|
| 53 |
pub(crate) const MAX_BSON_SIZE: i32 = 16 * 1024 * 1024; |
| 54 |
pub(crate) const MIN_BSON_DOCUMENT_SIZE: i32 = 4 + 1; // 4 bytes for length, one byte for null terminator |
| 55 |
pub(crate) const MIN_BSON_STRING_SIZE: i32 = 4 + 1; // 4 bytes for length, one byte for null terminator |
| 56 |
pub(crate) const MIN_CODE_WITH_SCOPE_SIZE: i32 = 4 + MIN_BSON_STRING_SIZE + MIN_BSON_DOCUMENT_SIZE; |
| 57 |
|
| 58 |
/// Hint provided to the deserializer via `deserialize_newtype_struct` as to the type of thing |
| 59 |
/// being deserialized. |
| 60 |
#[derive(Debug, Clone, Copy)] |
| 61 |
enum DeserializerHint { |
| 62 |
/// No hint provided, deserialize normally. |
| 63 |
None, |
| 64 |
|
| 65 |
/// The type being deserialized expects the BSON to contain a binary value with the provided |
| 66 |
/// subtype. This is currently used to deserialize [`bson::Uuid`] values. |
| 67 |
BinarySubtype(BinarySubtype), |
| 68 |
|
| 69 |
/// The type being deserialized is raw BSON, meaning no allocations should occur as part of |
| 70 |
/// deserializing and everything should be visited via borrowing or [`Copy`] if possible. |
| 71 |
RawBson, |
| 72 |
} |
| 73 |
|
| 74 |
pub(crate) fn read_string<R: Read + ?Sized>(reader: &mut R, utf8_lossy: bool) -> Result<String> { |
| 75 |
let len = read_i32(reader)?; |
| 76 |
|
| 77 |
// UTF-8 String must have at least 1 byte (the last 0x00). |
| 78 |
if len < 1 { |
| 79 |
return Err(Error::invalid_length( |
| 80 |
len as usize, |
| 81 |
&"UTF-8 string must have at least 1 byte", |
| 82 |
)); |
| 83 |
} |
| 84 |
|
| 85 |
let s = if utf8_lossy { |
| 86 |
let mut buf = Vec::with_capacity(len as usize - 1); |
| 87 |
reader.take(len as u64 - 1).read_to_end(&mut buf)?; |
| 88 |
String::from_utf8_lossy(&buf).to_string() |
| 89 |
} else { |
| 90 |
let mut s = String::with_capacity(len as usize - 1); |
| 91 |
reader.take(len as u64 - 1).read_to_string(&mut s)?; |
| 92 |
s |
| 93 |
}; |
| 94 |
|
| 95 |
// read the null terminator |
| 96 |
if read_u8(reader)? != 0 { |
| 97 |
return Err(Error::invalid_length( |
| 98 |
len as usize, |
| 99 |
&"contents of string longer than provided length", |
| 100 |
)); |
| 101 |
} |
| 102 |
|
| 103 |
Ok(s) |
| 104 |
} |
| 105 |
|
| 106 |
pub(crate) fn read_bool<R: Read>(mut reader: R) -> Result<bool> { |
| 107 |
let val = read_u8(&mut reader)?; |
| 108 |
if val > 1 { |
| 109 |
return Err(Error::invalid_value( |
| 110 |
Unexpected::Unsigned(val as u64), |
| 111 |
&"boolean must be stored as 0 or 1", |
| 112 |
)); |
| 113 |
} |
| 114 |
|
| 115 |
Ok(val != 0) |
| 116 |
} |
| 117 |
|
| 118 |
#[inline] |
| 119 |
pub(crate) fn read_u8<R: Read + ?Sized>(reader: &mut R) -> Result<u8> { |
| 120 |
let mut buf = [0; 1]; |
| 121 |
reader.read_exact(&mut buf)?; |
| 122 |
Ok(u8::from_le_bytes(buf)) |
| 123 |
} |
| 124 |
|
| 125 |
#[inline] |
| 126 |
pub(crate) fn read_i32<R: Read + ?Sized>(reader: &mut R) -> Result<i32> { |
| 127 |
let mut buf = [0; 4]; |
| 128 |
reader.read_exact(&mut buf)?; |
| 129 |
Ok(i32::from_le_bytes(buf)) |
| 130 |
} |
| 131 |
|
| 132 |
#[inline] |
| 133 |
pub(crate) fn read_i64<R: Read + ?Sized>(reader: &mut R) -> Result<i64> { |
| 134 |
let mut buf = [0; 8]; |
| 135 |
reader.read_exact(&mut buf)?; |
| 136 |
Ok(i64::from_le_bytes(buf)) |
| 137 |
} |
| 138 |
|
| 139 |
#[inline] |
| 140 |
fn read_f64<R: Read + ?Sized>(reader: &mut R) -> Result<f64> { |
| 141 |
let mut buf = [0; 8]; |
| 142 |
reader.read_exact(&mut buf)?; |
| 143 |
Ok(f64::from_le_bytes(buf)) |
| 144 |
} |
| 145 |
|
| 146 |
/// Placeholder decoder for `Decimal128`. Reads 128 bits and just stores them, does no validation or |
| 147 |
/// parsing. |
| 148 |
#[inline] |
| 149 |
fn read_f128<R: Read + ?Sized>(reader: &mut R) -> Result<Decimal128> { |
| 150 |
let mut buf = [0u8; 128 / 8]; |
| 151 |
reader.read_exact(&mut buf)?; |
| 152 |
Ok(Decimal128 { bytes: buf }) |
| 153 |
} |
| 154 |
|
| 155 |
impl<'a> RawBinaryRef<'a> { |
| 156 |
pub(crate) fn from_slice_with_len_and_payload( |
| 157 |
mut bytes: &'a [u8], |
| 158 |
mut len: i32, |
| 159 |
subtype: BinarySubtype, |
| 160 |
) -> Result<Self> { |
| 161 |
if !(0..=MAX_BSON_SIZE).contains(&len) { |
| 162 |
return Err(Error::invalid_length( |
| 163 |
len as usize, |
| 164 |
&format!("binary length must be between 0 and {}", MAX_BSON_SIZE).as_str(), |
| 165 |
)); |
| 166 |
} else if len as usize > bytes.len() { |
| 167 |
return Err(Error::invalid_length( |
| 168 |
len as usize, |
| 169 |
&format!( |
| 170 |
"binary length {} exceeds buffer length {}", |
| 171 |
len, |
| 172 |
bytes.len() |
| 173 |
) |
| 174 |
.as_str(), |
| 175 |
)); |
| 176 |
} |
| 177 |
|
| 178 |
// Skip length data in old binary. |
| 179 |
if let BinarySubtype::BinaryOld = subtype { |
| 180 |
let data_len = read_i32(&mut bytes)?; |
| 181 |
|
| 182 |
if data_len + 4 != len { |
| 183 |
return Err(Error::invalid_length( |
| 184 |
data_len as usize, |
| 185 |
&"0x02 length did not match top level binary length", |
| 186 |
)); |
| 187 |
} |
| 188 |
|
| 189 |
len -= 4; |
| 190 |
} |
| 191 |
|
| 192 |
Ok(Self { |
| 193 |
bytes: &bytes[0..len as usize], |
| 194 |
subtype, |
| 195 |
}) |
| 196 |
} |
| 197 |
} |
| 198 |
|
| 199 |
impl Timestamp { |
| 200 |
pub(crate) fn from_reader<R: Read>(mut reader: R) -> Result<Self> { |
| 201 |
let mut bytes = [0; 8]; |
| 202 |
reader.read_exact(&mut bytes)?; |
| 203 |
Ok(Timestamp::from_le_bytes(bytes)) |
| 204 |
} |
| 205 |
} |
| 206 |
|
| 207 |
impl ObjectId { |
| 208 |
pub(crate) fn from_reader<R: Read>(mut reader: R) -> Result<Self> { |
| 209 |
let mut buf = [0u8; 12]; |
| 210 |
reader.read_exact(&mut buf)?; |
| 211 |
Ok(Self::from_bytes(buf)) |
| 212 |
} |
| 213 |
} |
| 214 |
|
| 215 |
/// Deserialize a `T` from the provided [`Bson`] value. |
| 216 |
/// |
| 217 |
/// The [`Deserializer`] used by this function presents itself as human readable, whereas the |
| 218 |
/// one used in [`from_slice`] does not. This means that this function may deserialize differently |
| 219 |
/// than [`from_slice`] for types that change their deserialization logic depending on whether |
| 220 |
/// the format is human readable or not. To deserialize from [`Bson`] with a deserializer that |
| 221 |
/// presents itself as not human readable, use [`from_bson_with_options`] with |
| 222 |
/// [`DeserializerOptions::human_readable`] set to false. |
| 223 |
pub fn from_bson<T>(bson: Bson) -> Result<T> |
| 224 |
where |
| 225 |
T: DeserializeOwned, |
| 226 |
{ |
| 227 |
let de = Deserializer::new(bson); |
| 228 |
Deserialize::deserialize(de) |
| 229 |
} |
| 230 |
|
| 231 |
/// Deserialize a `T` from the provided [`Bson`] value, configuring the underlying |
| 232 |
/// deserializer with the provided options. |
| 233 |
/// ``` |
| 234 |
/// # use serde::Deserialize; |
| 235 |
/// # use bson::{bson, DeserializerOptions}; |
| 236 |
/// #[derive(Debug, Deserialize, PartialEq)] |
| 237 |
/// struct MyData { |
| 238 |
/// a: String, |
| 239 |
/// } |
| 240 |
/// |
| 241 |
/// let bson = bson!({ "a": "hello" }); |
| 242 |
/// let options = DeserializerOptions::builder().human_readable(false).build(); |
| 243 |
/// let data: MyData = bson::from_bson_with_options(bson, options)?; |
| 244 |
/// assert_eq!(data, MyData { a: "hello".to_string() }); |
| 245 |
/// # Ok::<(), Box<dyn std::error::Error>>(()) |
| 246 |
/// ``` |
| 247 |
pub fn from_bson_with_options<T>(bson: Bson, options: DeserializerOptions) -> Result<T> |
| 248 |
where |
| 249 |
T: DeserializeOwned, |
| 250 |
{ |
| 251 |
let de = Deserializer::new_with_options(bson, options); |
| 252 |
Deserialize::deserialize(de) |
| 253 |
} |
| 254 |
|
| 255 |
/// Deserialize a `T` from the provided [`Document`]. |
| 256 |
/// |
| 257 |
/// The [`Deserializer`] used by this function presents itself as human readable, whereas the |
| 258 |
/// one used in [`from_slice`] does not. This means that this function may deserialize differently |
| 259 |
/// than [`from_slice`] for types that change their deserialization logic depending on whether |
| 260 |
/// the format is human readable or not. To deserialize from [`Document`] with a deserializer that |
| 261 |
/// presents itself as not human readable, use [`from_document_with_options`] with |
| 262 |
/// [`DeserializerOptions::human_readable`] set to false. |
| 263 |
pub fn from_document<T>(doc: Document) -> Result<T> |
| 264 |
where |
| 265 |
T: DeserializeOwned, |
| 266 |
{ |
| 267 |
from_bson(Bson::Document(doc)) |
| 268 |
} |
| 269 |
|
| 270 |
/// Deserialize a `T` from the provided [`Document`], configuring the underlying |
| 271 |
/// deserializer with the provided options. |
| 272 |
/// ``` |
| 273 |
/// # use serde::Deserialize; |
| 274 |
/// # use bson::{doc, DeserializerOptions}; |
| 275 |
/// #[derive(Debug, Deserialize, PartialEq)] |
| 276 |
/// struct MyData { |
| 277 |
/// a: String, |
| 278 |
/// } |
| 279 |
/// |
| 280 |
/// let doc = doc! { "a": "hello" }; |
| 281 |
/// let options = DeserializerOptions::builder().human_readable(false).build(); |
| 282 |
/// let data: MyData = bson::from_document_with_options(doc, options)?; |
| 283 |
/// assert_eq!(data, MyData { a: "hello".to_string() }); |
| 284 |
/// # Ok::<(), Box<dyn std::error::Error>>(()) |
| 285 |
/// ``` |
| 286 |
pub fn from_document_with_options<T>(doc: Document, options: DeserializerOptions) -> Result<T> |
| 287 |
where |
| 288 |
T: DeserializeOwned, |
| 289 |
{ |
| 290 |
let de = Deserializer::new_with_options(Bson::Document(doc), options); |
| 291 |
Deserialize::deserialize(de) |
| 292 |
} |
| 293 |
|
| 294 |
fn reader_to_vec<R: Read>(mut reader: R) -> Result<Vec<u8>> { |
| 295 |
let length = read_i32(&mut reader)?; |
| 296 |
|
| 297 |
if length < MIN_BSON_DOCUMENT_SIZE { |
| 298 |
return Err(Error::custom("document size too small")); |
| 299 |
} |
| 300 |
|
| 301 |
let mut bytes = Vec::with_capacity(length as usize); |
| 302 |
write_i32(&mut bytes, length).map_err(Error::custom)?; |
| 303 |
|
| 304 |
reader.take(length as u64 - 4).read_to_end(&mut bytes)?; |
| 305 |
Ok(bytes) |
| 306 |
} |
| 307 |
|
| 308 |
/// Deserialize an instance of type `T` from an I/O stream of BSON. |
| 309 |
pub fn from_reader<R, T>(reader: R) -> Result<T> |
| 310 |
where |
| 311 |
T: DeserializeOwned, |
| 312 |
R: Read, |
| 313 |
{ |
| 314 |
let bytes = reader_to_vec(reader)?; |
| 315 |
from_slice(bytes.as_slice()) |
| 316 |
} |
| 317 |
|
| 318 |
/// Deserialize an instance of type `T` from an I/O stream of BSON, replacing any invalid UTF-8 |
| 319 |
/// sequences with the Unicode replacement character. |
| 320 |
/// |
| 321 |
/// This is mainly useful when reading raw BSON returned from a MongoDB server, which |
| 322 |
/// in rare cases can contain invalidly truncated strings (<https://jira.mongodb.org/browse/SERVER-24007>). |
| 323 |
/// For most use cases, [`crate::from_reader`] can be used instead. |
| 324 |
pub fn from_reader_utf8_lossy<R, T>(reader: R) -> Result<T> |
| 325 |
where |
| 326 |
T: DeserializeOwned, |
| 327 |
R: Read, |
| 328 |
{ |
| 329 |
let bytes = reader_to_vec(reader)?; |
| 330 |
from_slice_utf8_lossy(bytes.as_slice()) |
| 331 |
} |
| 332 |
|
| 333 |
/// Deserialize an instance of type `T` from a slice of BSON bytes. |
| 334 |
pub fn from_slice<'de, T>(bytes: &'de [u8]) -> Result<T> |
| 335 |
where |
| 336 |
T: Deserialize<'de>, |
| 337 |
{ |
| 338 |
let mut deserializer = raw::Deserializer::new(bytes, false); |
| 339 |
T::deserialize(&mut deserializer) |
| 340 |
} |
| 341 |
|
| 342 |
/// Deserialize an instance of type `T` from a slice of BSON bytes, replacing any invalid UTF-8 |
| 343 |
/// sequences with the Unicode replacement character. |
| 344 |
/// |
| 345 |
/// This is mainly useful when reading raw BSON returned from a MongoDB server, which |
| 346 |
/// in rare cases can contain invalidly truncated strings (<https://jira.mongodb.org/browse/SERVER-24007>). |
| 347 |
/// For most use cases, [`crate::from_slice`] can be used instead. |
| 348 |
pub fn from_slice_utf8_lossy<'de, T>(bytes: &'de [u8]) -> Result<T> |
| 349 |
where |
| 350 |
T: Deserialize<'de>, |
| 351 |
{ |
| 352 |
let mut deserializer = raw::Deserializer::new(bytes, true); |
| 353 |
T::deserialize(&mut deserializer) |
| 354 |
} |