Debian Codegraph @

src/ser/raw/mod.rs

raw
1 mod document_serializer;
2 mod value_serializer;
3
4 use std::io::Write;
5
6 use serde::{
7 ser::{Error as SerdeError, SerializeMap, SerializeStruct},
8 Serialize,
9 };
10
11 use self::value_serializer::{ValueSerializer, ValueType};
12
13 use super::{write_binary, write_cstring, write_f64, write_i32, write_i64, write_string};
14 use crate::{
15 raw::{RAW_ARRAY_NEWTYPE, RAW_DOCUMENT_NEWTYPE},
16 ser::{Error, Result},
17 spec::{BinarySubtype, ElementType},
18 uuid::UUID_NEWTYPE_NAME,
19 };
20 use document_serializer::DocumentSerializer;
21
22 /// Serializer used to convert a type `T` into raw BSON bytes.
23 pub(crate) struct Serializer {
24 bytes: Vec<u8>,
25
26 /// The index into `bytes` where the current element type will need to be stored.
27 /// This needs to be set retroactively because in BSON, the element type comes before the key,
28 /// but in serde, the serializer learns of the type after serializing the key.
29 type_index: usize,
30
31 /// Hint provided by the type being serialized.
32 hint: SerializerHint,
33 }
34
35 /// Various bits of information that the serialized type can provide to the serializer to
36 /// inform the purpose of the next serialization step.
37 #[derive(Debug, Clone, Copy)]
38 enum SerializerHint {
39 None,
40
41 /// The next call to `serialize_bytes` is for the purposes of serializing a UUID.
42 Uuid,
43
44 /// The next call to `serialize_bytes` is for the purposes of serializing a raw document.
45 RawDocument,
46
47 /// The next call to `serialize_bytes` is for the purposes of serializing a raw array.
48 RawArray,
49 }
50
51 impl SerializerHint {
52 fn take(&mut self) -> SerializerHint {
53 std::mem::replace(self, SerializerHint::None)
54 }
55 }
56
57 impl Serializer {
58 pub(crate) fn new() -> Self {
59 Self {
60 bytes: Vec::new(),
61 type_index: 0,
62 hint: SerializerHint::None,
63 }
64 }
65
66 /// Convert this serializer into the vec of the serialized bytes.
67 pub(crate) fn into_vec(self) -> Vec<u8> {
68 self.bytes
69 }
70
71 /// Reserve a spot for the element type to be set retroactively via `update_element_type`.
72 #[inline]
73 fn reserve_element_type(&mut self) {
74 self.type_index = self.bytes.len(); // record index
75 self.bytes.push(0); // push temporary placeholder
76 }
77
78 /// Retroactively set the element type of the most recently serialized element.
79 #[inline]
80 fn update_element_type(&mut self, t: ElementType) -> Result<()> {
81 if self.type_index == 0 {
82 if matches!(t, ElementType::EmbeddedDocument) {
83 // don't need to set the element type for the top level document
84 return Ok(());
85 } else {
86 return Err(Error::custom(format!(
87 "attempted to encode a non-document type at the top level: {:?}",
88 t
89 )));
90 }
91 }
92
93 self.bytes[self.type_index] = t as u8;
94 Ok(())
95 }
96
97 /// Replace an i32 value at the given index with the given value.
98 #[inline]
99 fn replace_i32(&mut self, at: usize, with: i32) {
100 let portion = &mut self.bytes[at..at + 4];
101 portion.copy_from_slice(&with.to_le_bytes());
102 }
103 }
104
105 impl<'a> serde::Serializer for &'a mut Serializer {
106 type Ok = ();
107 type Error = Error;
108
109 type SerializeSeq = DocumentSerializer<'a>;
110 type SerializeTuple = DocumentSerializer<'a>;
111 type SerializeTupleStruct = DocumentSerializer<'a>;
112 type SerializeTupleVariant = VariantSerializer<'a>;
113 type SerializeMap = DocumentSerializer<'a>;
114 type SerializeStruct = StructSerializer<'a>;
115 type SerializeStructVariant = VariantSerializer<'a>;
116
117 fn is_human_readable(&self) -> bool {
118 false
119 }
120
121 #[inline]
122 fn serialize_bool(self, v: bool) -> Result<Self::Ok> {
123 self.update_element_type(ElementType::Boolean)?;
124 self.bytes.push(v as u8);
125 Ok(())
126 }
127
128 #[inline]
129 fn serialize_i8(self, v: i8) -> Result<Self::Ok> {
130 self.serialize_i32(v.into())
131 }
132
133 #[inline]
134 fn serialize_i16(self, v: i16) -> Result<Self::Ok> {
135 self.serialize_i32(v.into())
136 }
137
138 #[inline]
139 fn serialize_i32(self, v: i32) -> Result<Self::Ok> {
140 self.update_element_type(ElementType::Int32)?;
141 write_i32(&mut self.bytes, v)?;
142 Ok(())
143 }
144
145 #[inline]
146 fn serialize_i64(self, v: i64) -> Result<Self::Ok> {
147 self.update_element_type(ElementType::Int64)?;
148 write_i64(&mut self.bytes, v)?;
149 Ok(())
150 }
151
152 #[inline]
153 fn serialize_u8(self, v: u8) -> Result<Self::Ok> {
154 self.serialize_i32(v.into())
155 }
156
157 #[inline]
158 fn serialize_u16(self, v: u16) -> Result<Self::Ok> {
159 self.serialize_i32(v.into())
160 }
161
162 #[inline]
163 fn serialize_u32(self, v: u32) -> Result<Self::Ok> {
164 self.serialize_i64(v.into())
165 }
166
167 #[inline]
168 fn serialize_u64(self, v: u64) -> Result<Self::Ok> {
169 use std::convert::TryFrom;
170
171 match i64::try_from(v) {
172 Ok(ivalue) => self.serialize_i64(ivalue),
173 Err(_) => Err(Error::UnsignedIntegerExceededRange(v)),
174 }
175 }
176
177 #[inline]
178 fn serialize_f32(self, v: f32) -> Result<Self::Ok> {
179 self.serialize_f64(v.into())
180 }
181
182 #[inline]
183 fn serialize_f64(self, v: f64) -> Result<Self::Ok> {
184 self.update_element_type(ElementType::Double)?;
185 write_f64(&mut self.bytes, v)
186 }
187
188 #[inline]
189 fn serialize_char(self, v: char) -> Result<Self::Ok> {
190 let mut s = String::new();
191 s.push(v);
192 self.serialize_str(&s)
193 }
194
195 #[inline]
196 fn serialize_str(self, v: &str) -> Result<Self::Ok> {
197 self.update_element_type(ElementType::String)?;
198 write_string(&mut self.bytes, v)
199 }
200
201 #[inline]
202 fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok> {
203 match self.hint.take() {
204 SerializerHint::RawDocument => {
205 self.update_element_type(ElementType::EmbeddedDocument)?;
206 self.bytes.write_all(v)?;
207 }
208 SerializerHint::RawArray => {
209 self.update_element_type(ElementType::Array)?;
210 self.bytes.write_all(v)?;
211 }
212 hint => {
213 self.update_element_type(ElementType::Binary)?;
214
215 let subtype = if matches!(hint, SerializerHint::Uuid) {
216 BinarySubtype::Uuid
217 } else {
218 BinarySubtype::Generic
219 };
220
221 write_binary(&mut self.bytes, v, subtype)?;
222 }
223 };
224 Ok(())
225 }
226
227 #[inline]
228 fn serialize_none(self) -> Result<Self::Ok> {
229 self.update_element_type(ElementType::Null)?;
230 Ok(())
231 }
232
233 #[inline]
234 fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Self::Ok>
235 where
236 T: serde::Serialize,
237 {
238 value.serialize(self)
239 }
240
241 #[inline]
242 fn serialize_unit(self) -> Result<Self::Ok> {
243 self.serialize_none()
244 }
245
246 #[inline]
247 fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok> {
248 self.serialize_unit()
249 }
250
251 #[inline]
252 fn serialize_unit_variant(
253 self,
254 _name: &'static str,
255 _variant_index: u32,
256 variant: &'static str,
257 ) -> Result<Self::Ok> {
258 self.serialize_str(variant)
259 }
260
261 #[inline]
262 fn serialize_newtype_struct<T: ?Sized>(self, name: &'static str, value: &T) -> Result<Self::Ok>
263 where
264 T: serde::Serialize,
265 {
266 match name {
267 UUID_NEWTYPE_NAME => self.hint = SerializerHint::Uuid,
268 RAW_DOCUMENT_NEWTYPE => self.hint = SerializerHint::RawDocument,
269 RAW_ARRAY_NEWTYPE => self.hint = SerializerHint::RawArray,
270 _ => {}
271 }
272 value.serialize(self)
273 }
274
275 #[inline]
276 fn serialize_newtype_variant<T: ?Sized>(
277 self,
278 _name: &'static str,
279 _variant_index: u32,
280 variant: &'static str,
281 value: &T,
282 ) -> Result<Self::Ok>
283 where
284 T: serde::Serialize,
285 {
286 self.update_element_type(ElementType::EmbeddedDocument)?;
287 let mut d = DocumentSerializer::start(&mut *self)?;
288 d.serialize_entry(variant, value)?;
289 d.end_doc()?;
290 Ok(())
291 }
292
293 #[inline]
294 fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
295 self.update_element_type(ElementType::Array)?;
296 DocumentSerializer::start(&mut *self)
297 }
298
299 #[inline]
300 fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
301 self.serialize_seq(Some(len))
302 }
303
304 #[inline]
305 fn serialize_tuple_struct(
306 self,
307 _name: &'static str,
308 len: usize,
309 ) -> Result<Self::SerializeTupleStruct> {
310 self.serialize_seq(Some(len))
311 }
312
313 #[inline]
314 fn serialize_tuple_variant(
315 self,
316 _name: &'static str,
317 _variant_index: u32,
318 variant: &'static str,
319 _len: usize,
320 ) -> Result<Self::SerializeTupleVariant> {
321 self.update_element_type(ElementType::EmbeddedDocument)?;
322 VariantSerializer::start(&mut *self, variant, VariantInnerType::Tuple)
323 }
324
325 #[inline]
326 fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
327 self.update_element_type(ElementType::EmbeddedDocument)?;
328 DocumentSerializer::start(&mut *self)
329 }
330
331 #[inline]
332 fn serialize_struct(self, name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
333 let value_type = match name {
334 "$oid" => Some(ValueType::ObjectId),
335 "$date" => Some(ValueType::DateTime),
336 "$binary" => Some(ValueType::Binary),
337 "$timestamp" => Some(ValueType::Timestamp),
338 "$minKey" => Some(ValueType::MinKey),
339 "$maxKey" => Some(ValueType::MaxKey),
340 "$code" => Some(ValueType::JavaScriptCode),
341 "$codeWithScope" => Some(ValueType::JavaScriptCodeWithScope),
342 "$symbol" => Some(ValueType::Symbol),
343 "$undefined" => Some(ValueType::Undefined),
344 "$regularExpression" => Some(ValueType::RegularExpression),
345 "$dbPointer" => Some(ValueType::DbPointer),
346 "$numberDecimal" => Some(ValueType::Decimal128),
347 _ => None,
348 };
349
350 self.update_element_type(
351 value_type
352 .map(Into::into)
353 .unwrap_or(ElementType::EmbeddedDocument),
354 )?;
355 match value_type {
356 Some(vt) => Ok(StructSerializer::Value(ValueSerializer::new(self, vt))),
357 None => Ok(StructSerializer::Document(DocumentSerializer::start(self)?)),
358 }
359 }
360
361 #[inline]
362 fn serialize_struct_variant(
363 self,
364 _name: &'static str,
365 _variant_index: u32,
366 variant: &'static str,
367 _len: usize,
368 ) -> Result<Self::SerializeStructVariant> {
369 self.update_element_type(ElementType::EmbeddedDocument)?;
370 VariantSerializer::start(&mut *self, variant, VariantInnerType::Struct)
371 }
372 }
373
374 pub(crate) enum StructSerializer<'a> {
375 /// Serialize a BSON value currently represented in serde as a struct (e.g. ObjectId)
376 Value(ValueSerializer<'a>),
377
378 /// Serialize the struct as a document.
379 Document(DocumentSerializer<'a>),
380 }
381
382 impl<'a> SerializeStruct for StructSerializer<'a> {
383 type Ok = ();
384 type Error = Error;
385
386 #[inline]
387 fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<()>
388 where
389 T: Serialize,
390 {
391 match self {
392 StructSerializer::Value(ref mut v) => (&mut *v).serialize_field(key, value),
393 StructSerializer::Document(d) => d.serialize_field(key, value),
394 }
395 }
396
397 #[inline]
398 fn end(self) -> Result<Self::Ok> {
399 match self {
400 StructSerializer::Document(d) => SerializeStruct::end(d),
401 StructSerializer::Value(mut v) => v.end(),
402 }
403 }
404 }
405
406 enum VariantInnerType {
407 Tuple,
408 Struct,
409 }
410
411 /// Serializer used for enum variants, including both tuple (e.g. Foo::Bar(1, 2, 3)) and
412 /// struct (e.g. Foo::Bar { a: 1 }).
413 pub(crate) struct VariantSerializer<'a> {
414 root_serializer: &'a mut Serializer,
415
416 /// Variants are serialized as documents of the form `{ <variant name>: <document or array> }`,
417 /// and `doc_start` indicates the index at which the outer document begins.
418 doc_start: usize,
419
420 /// `inner_start` indicates the index at which the inner document or array begins.
421 inner_start: usize,
422
423 /// How many elements have been serialized in the inner document / array so far.
424 num_elements_serialized: usize,
425 }
426
427 impl<'a> VariantSerializer<'a> {
428 fn start(
429 rs: &'a mut Serializer,
430 variant: &'static str,
431 inner_type: VariantInnerType,
432 ) -> Result<Self> {
433 let doc_start = rs.bytes.len();
434 // write placeholder length for document, will be updated at end
435 write_i32(&mut rs.bytes, 0)?;
436
437 let inner = match inner_type {
438 VariantInnerType::Struct => ElementType::EmbeddedDocument,
439 VariantInnerType::Tuple => ElementType::Array,
440 };
441 rs.bytes.push(inner as u8);
442 write_cstring(&mut rs.bytes, variant)?;
443 let inner_start = rs.bytes.len();
444 // write placeholder length for inner, will be updated at end
445 write_i32(&mut rs.bytes, 0)?;
446
447 Ok(Self {
448 root_serializer: rs,
449 num_elements_serialized: 0,
450 doc_start,
451 inner_start,
452 })
453 }
454
455 #[inline]
456 fn serialize_element<T>(&mut self, k: &str, v: &T) -> Result<()>
457 where
458 T: Serialize + ?Sized,
459 {
460 self.root_serializer.reserve_element_type();
461 write_cstring(&mut self.root_serializer.bytes, k)?;
462 v.serialize(&mut *self.root_serializer)?;
463
464 self.num_elements_serialized += 1;
465 Ok(())
466 }
467
468 #[inline]
469 fn end_both(self) -> Result<()> {
470 // null byte for the inner
471 self.root_serializer.bytes.push(0);
472 let arr_length = (self.root_serializer.bytes.len() - self.inner_start) as i32;
473 self.root_serializer
474 .replace_i32(self.inner_start, arr_length);
475
476 // null byte for document
477 self.root_serializer.bytes.push(0);
478 let doc_length = (self.root_serializer.bytes.len() - self.doc_start) as i32;
479 self.root_serializer.replace_i32(self.doc_start, doc_length);
480 Ok(())
481 }
482 }
483
484 impl<'a> serde::ser::SerializeTupleVariant for VariantSerializer<'a> {
485 type Ok = ();
486
487 type Error = Error;
488
489 #[inline]
490 fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>
491 where
492 T: Serialize,
493 {
494 self.serialize_element(format!("{}", self.num_elements_serialized).as_str(), value)
495 }
496
497 #[inline]
498 fn end(self) -> Result<Self::Ok> {
499 self.end_both()
500 }
501 }
502
503 impl<'a> serde::ser::SerializeStructVariant for VariantSerializer<'a> {
504 type Ok = ();
505
506 type Error = Error;
507
508 #[inline]
509 fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<()>
510 where
511 T: Serialize,
512 {
513 self.serialize_element(key, value)
514 }
515
516 #[inline]
517 fn end(self) -> Result<Self::Ok> {
518 self.end_both()
519 }
520 }