Debian Codegraph @

src/ser/raw/value_serializer.rs

raw
1 use std::{convert::TryFrom, io::Write};
2
3 use serde::{
4 ser::{Error as SerdeError, Impossible, SerializeMap, SerializeStruct},
5 Serialize,
6 };
7
8 use crate::{
9 oid::ObjectId,
10 raw::RAW_DOCUMENT_NEWTYPE,
11 ser::{write_binary, write_cstring, write_i32, write_i64, write_string, Error, Result},
12 spec::{BinarySubtype, ElementType},
13 RawDocument,
14 RawJavaScriptCodeWithScopeRef,
15 };
16
17 use super::{document_serializer::DocumentSerializer, Serializer};
18
19 /// A serializer used specifically for serializing the serde-data-model form of a BSON type (e.g.
20 /// [`Binary`]) to raw bytes.
21 pub(crate) struct ValueSerializer<'a> {
22 root_serializer: &'a mut Serializer,
23 state: SerializationStep,
24 }
25
26 /// State machine used to track which step in the serialization of a given type the serializer is
27 /// currently on.
28 #[derive(Debug)]
29 enum SerializationStep {
30 Oid,
31
32 DateTime,
33 DateTimeNumberLong,
34
35 Binary,
36 /// This step can either transition to the raw or base64 steps depending
37 /// on whether a string or bytes are serialized.
38 BinaryBytes,
39 BinarySubType {
40 base64: String,
41 },
42 RawBinarySubType {
43 bytes: Vec<u8>,
44 },
45
46 Symbol,
47
48 RegEx,
49 RegExPattern,
50 RegExOptions,
51
52 Timestamp,
53 TimestampTime,
54 TimestampIncrement {
55 time: i64,
56 },
57
58 DbPointer,
59 DbPointerRef,
60 DbPointerId,
61
62 Code,
63
64 CodeWithScopeCode,
65 CodeWithScopeScope {
66 code: String,
67 raw: bool,
68 },
69
70 MinKey,
71
72 MaxKey,
73
74 Undefined,
75
76 Decimal128,
77 Decimal128Value,
78
79 Done,
80 }
81
82 /// Enum of BSON "value" types that this serializer can serialize.
83 #[derive(Debug, Clone, Copy)]
84 pub(super) enum ValueType {
85 DateTime,
86 Binary,
87 ObjectId,
88 Symbol,
89 RegularExpression,
90 Timestamp,
91 DbPointer,
92 JavaScriptCode,
93 JavaScriptCodeWithScope,
94 MinKey,
95 MaxKey,
96 Decimal128,
97 Undefined,
98 }
99
100 impl From<ValueType> for ElementType {
101 fn from(vt: ValueType) -> Self {
102 match vt {
103 ValueType::Binary => ElementType::Binary,
104 ValueType::DateTime => ElementType::DateTime,
105 ValueType::DbPointer => ElementType::DbPointer,
106 ValueType::Decimal128 => ElementType::Decimal128,
107 ValueType::Symbol => ElementType::Symbol,
108 ValueType::RegularExpression => ElementType::RegularExpression,
109 ValueType::Timestamp => ElementType::Timestamp,
110 ValueType::JavaScriptCode => ElementType::JavaScriptCode,
111 ValueType::JavaScriptCodeWithScope => ElementType::JavaScriptCodeWithScope,
112 ValueType::MaxKey => ElementType::MaxKey,
113 ValueType::MinKey => ElementType::MinKey,
114 ValueType::Undefined => ElementType::Undefined,
115 ValueType::ObjectId => ElementType::ObjectId,
116 }
117 }
118 }
119
120 impl<'a> ValueSerializer<'a> {
121 pub(super) fn new(rs: &'a mut Serializer, value_type: ValueType) -> Self {
122 let state = match value_type {
123 ValueType::DateTime => SerializationStep::DateTime,
124 ValueType::Binary => SerializationStep::Binary,
125 ValueType::ObjectId => SerializationStep::Oid,
126 ValueType::Symbol => SerializationStep::Symbol,
127 ValueType::RegularExpression => SerializationStep::RegEx,
128 ValueType::Timestamp => SerializationStep::Timestamp,
129 ValueType::DbPointer => SerializationStep::DbPointer,
130 ValueType::JavaScriptCode => SerializationStep::Code,
131 ValueType::JavaScriptCodeWithScope => SerializationStep::CodeWithScopeCode,
132 ValueType::MinKey => SerializationStep::MinKey,
133 ValueType::MaxKey => SerializationStep::MaxKey,
134 ValueType::Decimal128 => SerializationStep::Decimal128,
135 ValueType::Undefined => SerializationStep::Undefined,
136 };
137 Self {
138 root_serializer: rs,
139 state,
140 }
141 }
142
143 fn invalid_step(&self, primitive_type: &'static str) -> Error {
144 Error::custom(format!(
145 "cannot serialize {} at step {:?}",
146 primitive_type, self.state
147 ))
148 }
149 }
150
151 impl<'a, 'b> serde::Serializer for &'b mut ValueSerializer<'a> {
152 type Ok = ();
153 type Error = Error;
154
155 type SerializeSeq = Impossible<(), Error>;
156 type SerializeTuple = Impossible<(), Error>;
157 type SerializeTupleStruct = Impossible<(), Error>;
158 type SerializeTupleVariant = Impossible<(), Error>;
159 type SerializeMap = CodeWithScopeSerializer<'b>;
160 type SerializeStruct = Self;
161 type SerializeStructVariant = Impossible<(), Error>;
162
163 #[inline]
164 fn serialize_bool(self, _v: bool) -> Result<Self::Ok> {
165 Err(self.invalid_step("bool"))
166 }
167
168 #[inline]
169 fn serialize_i8(self, _v: i8) -> Result<Self::Ok> {
170 Err(self.invalid_step("i8"))
171 }
172
173 #[inline]
174 fn serialize_i16(self, _v: i16) -> Result<Self::Ok> {
175 Err(self.invalid_step("i16"))
176 }
177
178 #[inline]
179 fn serialize_i32(self, _v: i32) -> Result<Self::Ok> {
180 Err(self.invalid_step("i32"))
181 }
182
183 #[inline]
184 fn serialize_i64(self, v: i64) -> Result<Self::Ok> {
185 match self.state {
186 SerializationStep::TimestampTime => {
187 self.state = SerializationStep::TimestampIncrement { time: v };
188 Ok(())
189 }
190 SerializationStep::TimestampIncrement { time } => {
191 let t = u32::try_from(time).map_err(Error::custom)?;
192 let i = u32::try_from(v).map_err(Error::custom)?;
193
194 write_i32(&mut self.root_serializer.bytes, i as i32)?;
195 write_i32(&mut self.root_serializer.bytes, t as i32)?;
196 Ok(())
197 }
198 _ => Err(self.invalid_step("i64")),
199 }
200 }
201
202 #[inline]
203 fn serialize_u8(self, v: u8) -> Result<Self::Ok> {
204 match self.state {
205 SerializationStep::RawBinarySubType { ref bytes } => {
206 write_binary(&mut self.root_serializer.bytes, bytes.as_slice(), v.into())?;
207 self.state = SerializationStep::Done;
208 Ok(())
209 }
210 _ => Err(self.invalid_step("u8")),
211 }
212 }
213
214 #[inline]
215 fn serialize_u16(self, _v: u16) -> Result<Self::Ok> {
216 Err(self.invalid_step("u16"))
217 }
218
219 #[inline]
220 fn serialize_u32(self, _v: u32) -> Result<Self::Ok> {
221 Err(self.invalid_step("u32"))
222 }
223
224 #[inline]
225 fn serialize_u64(self, _v: u64) -> Result<Self::Ok> {
226 Err(self.invalid_step("u64"))
227 }
228
229 #[inline]
230 fn serialize_f32(self, _v: f32) -> Result<Self::Ok> {
231 Err(self.invalid_step("f32"))
232 }
233
234 #[inline]
235 fn serialize_f64(self, _v: f64) -> Result<Self::Ok> {
236 Err(self.invalid_step("f64"))
237 }
238
239 #[inline]
240 fn serialize_char(self, _v: char) -> Result<Self::Ok> {
241 Err(self.invalid_step("char"))
242 }
243
244 fn serialize_str(self, v: &str) -> Result<Self::Ok> {
245 match &self.state {
246 SerializationStep::DateTimeNumberLong => {
247 let millis: i64 = v.parse().map_err(Error::custom)?;
248 write_i64(&mut self.root_serializer.bytes, millis)?;
249 }
250 SerializationStep::Oid => {
251 let oid = ObjectId::parse_str(v).map_err(Error::custom)?;
252 self.root_serializer.bytes.write_all(&oid.bytes())?;
253 }
254 SerializationStep::BinaryBytes => {
255 self.state = SerializationStep::BinarySubType {
256 base64: v.to_string(),
257 };
258 }
259 SerializationStep::BinarySubType { base64 } => {
260 let subtype_byte = hex::decode(v).map_err(Error::custom)?;
261 let subtype: BinarySubtype = subtype_byte[0].into();
262
263 let bytes = base64::decode(base64.as_str()).map_err(Error::custom)?;
264
265 write_binary(&mut self.root_serializer.bytes, bytes.as_slice(), subtype)?;
266 }
267 SerializationStep::Symbol | SerializationStep::DbPointerRef => {
268 write_string(&mut self.root_serializer.bytes, v)?;
269 }
270 SerializationStep::RegExPattern => {
271 write_cstring(&mut self.root_serializer.bytes, v)?;
272 }
273 SerializationStep::RegExOptions => {
274 let mut chars: Vec<_> = v.chars().collect();
275 chars.sort_unstable();
276
277 let sorted = chars.into_iter().collect::<String>();
278 write_cstring(&mut self.root_serializer.bytes, sorted.as_str())?;
279 }
280 SerializationStep::Code => {
281 write_string(&mut self.root_serializer.bytes, v)?;
282 }
283 SerializationStep::CodeWithScopeCode => {
284 self.state = SerializationStep::CodeWithScopeScope {
285 code: v.to_string(),
286 raw: false,
287 };
288 }
289 s => {
290 return Err(Error::custom(format!(
291 "can't serialize string for step {:?}",
292 s
293 )))
294 }
295 }
296 Ok(())
297 }
298
299 #[inline]
300 fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok> {
301 match self.state {
302 SerializationStep::Decimal128Value => {
303 self.root_serializer.bytes.write_all(v)?;
304 Ok(())
305 }
306 SerializationStep::BinaryBytes => {
307 self.state = SerializationStep::RawBinarySubType { bytes: v.to_vec() };
308 Ok(())
309 }
310 SerializationStep::CodeWithScopeScope { ref code, raw } if raw => {
311 let raw = RawJavaScriptCodeWithScopeRef {
312 code,
313 scope: RawDocument::from_bytes(v).map_err(Error::custom)?,
314 };
315 write_i32(&mut self.root_serializer.bytes, raw.len())?;
316 write_string(&mut self.root_serializer.bytes, code)?;
317 self.root_serializer.bytes.write_all(v)?;
318 self.state = SerializationStep::Done;
319 Ok(())
320 }
321 _ => Err(self.invalid_step("&[u8]")),
322 }
323 }
324
325 #[inline]
326 fn serialize_none(self) -> Result<Self::Ok> {
327 Err(self.invalid_step("none"))
328 }
329
330 #[inline]
331 fn serialize_some<T: ?Sized>(self, _value: &T) -> Result<Self::Ok>
332 where
333 T: Serialize,
334 {
335 Err(self.invalid_step("some"))
336 }
337
338 #[inline]
339 fn serialize_unit(self) -> Result<Self::Ok> {
340 Err(self.invalid_step("unit"))
341 }
342
343 #[inline]
344 fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok> {
345 Err(self.invalid_step("unit_struct"))
346 }
347
348 #[inline]
349 fn serialize_unit_variant(
350 self,
351 _name: &'static str,
352 _variant_index: u32,
353 _variant: &'static str,
354 ) -> Result<Self::Ok> {
355 Err(self.invalid_step("unit_variant"))
356 }
357
358 #[inline]
359 fn serialize_newtype_struct<T: ?Sized>(self, name: &'static str, value: &T) -> Result<Self::Ok>
360 where
361 T: Serialize,
362 {
363 match (&mut self.state, name) {
364 (
365 SerializationStep::CodeWithScopeScope {
366 code: _,
367 ref mut raw,
368 },
369 RAW_DOCUMENT_NEWTYPE,
370 ) => {
371 *raw = true;
372 value.serialize(self)
373 }
374 _ => Err(self.invalid_step("newtype_struct")),
375 }
376 }
377
378 #[inline]
379 fn serialize_newtype_variant<T: ?Sized>(
380 self,
381 _name: &'static str,
382 _variant_index: u32,
383 _variant: &'static str,
384 _value: &T,
385 ) -> Result<Self::Ok>
386 where
387 T: Serialize,
388 {
389 Err(self.invalid_step("newtype_variant"))
390 }
391
392 #[inline]
393 fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
394 Err(self.invalid_step("seq"))
395 }
396
397 #[inline]
398 fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
399 Err(self.invalid_step("newtype_tuple"))
400 }
401
402 #[inline]
403 fn serialize_tuple_struct(
404 self,
405 _name: &'static str,
406 _len: usize,
407 ) -> Result<Self::SerializeTupleStruct> {
408 Err(self.invalid_step("tuple_struct"))
409 }
410
411 #[inline]
412 fn serialize_tuple_variant(
413 self,
414 _name: &'static str,
415 _variant_index: u32,
416 _variant: &'static str,
417 _len: usize,
418 ) -> Result<Self::SerializeTupleVariant> {
419 Err(self.invalid_step("tuple_variant"))
420 }
421
422 #[inline]
423 fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
424 match self.state {
425 SerializationStep::CodeWithScopeScope { ref code, raw } if !raw => {
426 CodeWithScopeSerializer::start(code.as_str(), self.root_serializer)
427 }
428 _ => Err(self.invalid_step("map")),
429 }
430 }
431
432 #[inline]
433 fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
434 Ok(self)
435 }
436
437 #[inline]
438 fn serialize_struct_variant(
439 self,
440 _name: &'static str,
441 _variant_index: u32,
442 _variant: &'static str,
443 _len: usize,
444 ) -> Result<Self::SerializeStructVariant> {
445 Err(self.invalid_step("struct_variant"))
446 }
447
448 fn is_human_readable(&self) -> bool {
449 false
450 }
451 }
452
453 impl<'a, 'b> SerializeStruct for &'b mut ValueSerializer<'a> {
454 type Ok = ();
455 type Error = Error;
456
457 fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<()>
458 where
459 T: Serialize,
460 {
461 match (&self.state, key) {
462 (SerializationStep::DateTime, "$date") => {
463 self.state = SerializationStep::DateTimeNumberLong;
464 value.serialize(&mut **self)?;
465 }
466 (SerializationStep::DateTimeNumberLong, "$numberLong") => {
467 value.serialize(&mut **self)?;
468 self.state = SerializationStep::Done;
469 }
470 (SerializationStep::Oid, "$oid") => {
471 value.serialize(&mut **self)?;
472 self.state = SerializationStep::Done;
473 }
474 (SerializationStep::Binary, "$binary") => {
475 self.state = SerializationStep::BinaryBytes;
476 value.serialize(&mut **self)?;
477 }
478 (SerializationStep::BinaryBytes, key) if key == "bytes" || key == "base64" => {
479 // state is updated in serialize
480 value.serialize(&mut **self)?;
481 }
482 (SerializationStep::RawBinarySubType { .. }, "subType") => {
483 value.serialize(&mut **self)?;
484 self.state = SerializationStep::Done;
485 }
486 (SerializationStep::BinarySubType { .. }, "subType") => {
487 value.serialize(&mut **self)?;
488 self.state = SerializationStep::Done;
489 }
490 (SerializationStep::Symbol, "$symbol") => {
491 value.serialize(&mut **self)?;
492 self.state = SerializationStep::Done;
493 }
494 (SerializationStep::RegEx, "$regularExpression") => {
495 self.state = SerializationStep::RegExPattern;
496 value.serialize(&mut **self)?;
497 }
498 (SerializationStep::RegExPattern, "pattern") => {
499 value.serialize(&mut **self)?;
500 self.state = SerializationStep::RegExOptions;
501 }
502 (SerializationStep::RegExOptions, "options") => {
503 value.serialize(&mut **self)?;
504 self.state = SerializationStep::Done;
505 }
506 (SerializationStep::Timestamp, "$timestamp") => {
507 self.state = SerializationStep::TimestampTime;
508 value.serialize(&mut **self)?;
509 }
510 (SerializationStep::TimestampTime, "t") => {
511 // state is updated in serialize
512 value.serialize(&mut **self)?;
513 }
514 (SerializationStep::TimestampIncrement { .. }, "i") => {
515 value.serialize(&mut **self)?;
516 self.state = SerializationStep::Done;
517 }
518 (SerializationStep::DbPointer, "$dbPointer") => {
519 self.state = SerializationStep::DbPointerRef;
520 value.serialize(&mut **self)?;
521 }
522 (SerializationStep::DbPointerRef, "$ref") => {
523 value.serialize(&mut **self)?;
524 self.state = SerializationStep::DbPointerId;
525 }
526 (SerializationStep::DbPointerId, "$id") => {
527 self.state = SerializationStep::Oid;
528 value.serialize(&mut **self)?;
529 }
530 (SerializationStep::Code, "$code") => {
531 value.serialize(&mut **self)?;
532 self.state = SerializationStep::Done;
533 }
534 (SerializationStep::CodeWithScopeCode, "$code") => {
535 // state is updated in serialize
536 value.serialize(&mut **self)?;
537 }
538 (SerializationStep::CodeWithScopeScope { .. }, "$scope") => {
539 value.serialize(&mut **self)?;
540 self.state = SerializationStep::Done;
541 }
542 (SerializationStep::MinKey, "$minKey") => {
543 self.state = SerializationStep::Done;
544 }
545 (SerializationStep::MaxKey, "$maxKey") => {
546 self.state = SerializationStep::Done;
547 }
548 (SerializationStep::Undefined, "$undefined") => {
549 self.state = SerializationStep::Done;
550 }
551 (SerializationStep::Decimal128, "$numberDecimal")
552 | (SerializationStep::Decimal128, "$numberDecimalBytes") => {
553 self.state = SerializationStep::Decimal128Value;
554 value.serialize(&mut **self)?;
555 }
556 (SerializationStep::Decimal128Value, "$numberDecimal") => {
557 value.serialize(&mut **self)?;
558 self.state = SerializationStep::Done;
559 }
560 (SerializationStep::Done, k) => {
561 return Err(Error::custom(format!(
562 "expected to end serialization of type, got extra key \"{}\"",
563 k
564 )));
565 }
566 (state, k) => {
567 return Err(Error::custom(format!(
568 "mismatched serialization step and next key: {:?} + \"{}\"",
569 state, k
570 )));
571 }
572 }
573
574 Ok(())
575 }
576
577 #[inline]
578 fn end(self) -> Result<Self::Ok> {
579 Ok(())
580 }
581 }
582
583 pub(crate) struct CodeWithScopeSerializer<'a> {
584 start: usize,
585 doc: DocumentSerializer<'a>,
586 }
587
588 impl<'a> CodeWithScopeSerializer<'a> {
589 #[inline]
590 fn start(code: &str, rs: &'a mut Serializer) -> Result<Self> {
591 let start = rs.bytes.len();
592 write_i32(&mut rs.bytes, 0)?; // placeholder length
593 write_string(&mut rs.bytes, code)?;
594
595 let doc = DocumentSerializer::start(rs)?;
596 Ok(Self { start, doc })
597 }
598 }
599
600 impl<'a> SerializeMap for CodeWithScopeSerializer<'a> {
601 type Ok = ();
602 type Error = Error;
603
604 #[inline]
605 fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<()>
606 where
607 T: Serialize,
608 {
609 self.doc.serialize_key(key)
610 }
611
612 #[inline]
613 fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<()>
614 where
615 T: Serialize,
616 {
617 self.doc.serialize_value(value)
618 }
619
620 #[inline]
621 fn end(self) -> Result<Self::Ok> {
622 let result = self.doc.end_doc()?;
623
624 let total_len = (result.root_serializer.bytes.len() - self.start) as i32;
625 result.root_serializer.replace_i32(self.start, total_len);
626 Ok(())
627 }
628 }