Debian Codegraph @

src/raw/serde/seeded_visitor.rs

raw
1 use std::{borrow::Cow, convert::TryFrom, fmt::Formatter, ops::Range};
2
3 use serde::{
4 de::{DeserializeSeed, Error as SerdeError, MapAccess, SeqAccess, Visitor},
5 Deserializer,
6 };
7 use serde_bytes::ByteBuf;
8
9 use crate::{
10 de::MIN_BSON_DOCUMENT_SIZE,
11 extjson::models::{
12 BorrowedBinaryBody,
13 BorrowedDbPointerBody,
14 BorrowedRegexBody,
15 TimestampBody,
16 },
17 oid::ObjectId,
18 raw::{RAW_ARRAY_NEWTYPE, RAW_BSON_NEWTYPE, RAW_DOCUMENT_NEWTYPE},
19 spec::{BinarySubtype, ElementType},
20 RawDocumentBuf,
21 };
22
23 use super::CowStr;
24
25 /// A copy-on-write byte buffer containing raw BSON bytes. The inner value starts as `None` and
26 /// transitions to either `Cow::Borrowed` or `Cow::Owned` depending upon the data visited.
27 pub(crate) struct CowByteBuffer<'de>(pub(crate) Option<Cow<'de, [u8]>>);
28
29 impl<'de> CowByteBuffer<'de> {
30 /// Creates an new empty buffer.
31 pub(crate) fn new() -> Self {
32 Self(None)
33 }
34
35 /// The length of the buffer.
36 fn len(&self) -> usize {
37 match &self.0 {
38 Some(buffer) => buffer.len(),
39 None => 0,
40 }
41 }
42
43 /// Gets a mutable reference to the inner buffer, allocating a `Vec<u8>` and transitioning the
44 /// buffer's state as necessary.
45 fn get_owned_buffer(&mut self) -> &mut Vec<u8> {
46 self.0
47 .get_or_insert_with(|| Cow::Owned(Vec::new()))
48 .to_mut()
49 }
50
51 /// Appends a single byte to the buffer.
52 fn push_byte(&mut self, byte: u8) {
53 let buffer = self.get_owned_buffer();
54 buffer.push(byte);
55 }
56
57 /// Appends a slice of bytes to the buffer.
58 fn append_bytes(&mut self, bytes: &[u8]) {
59 let buffer = self.get_owned_buffer();
60 buffer.extend_from_slice(bytes);
61 }
62
63 /// Appends a slice of borrowed bytes to the buffer. If the buffer is currently `None`, it will
64 /// store a reference to the borrowed bytes; otherwise, it will copy the bytes to the
65 /// existing buffer.
66 fn append_borrowed_bytes(&mut self, bytes: &'de [u8]) {
67 match &mut self.0 {
68 Some(buffer) => buffer.to_mut().extend_from_slice(bytes),
69 None => self.0 = Some(Cow::Borrowed(bytes)),
70 }
71 }
72
73 /// Copies a slice of bytes into the given range. This method will panic if the range is out of
74 /// bounds.
75 fn copy_from_slice(&mut self, range: Range<usize>, slice: &[u8]) {
76 let buffer = self.get_owned_buffer();
77 buffer[range].copy_from_slice(slice);
78 }
79
80 /// Removes the bytes in the given range from the buffer. This method will panic if the range is
81 /// out of bounds.
82 fn drain(&mut self, range: Range<usize>) {
83 let buffer = self.get_owned_buffer();
84 buffer.drain(range);
85 }
86 }
87
88 pub(crate) struct SeededVisitor<'a, 'de> {
89 buffer: &'a mut CowByteBuffer<'de>,
90 }
91
92 impl<'a, 'de> DeserializeSeed<'de> for SeededVisitor<'a, 'de> {
93 type Value = ElementType;
94
95 fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
96 where
97 D: Deserializer<'de>,
98 {
99 deserializer.deserialize_newtype_struct(RAW_BSON_NEWTYPE, self)
100 }
101 }
102
103 impl<'a, 'de> DeserializeSeed<'de> for &mut SeededVisitor<'a, 'de> {
104 type Value = ElementType;
105
106 fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
107 where
108 D: Deserializer<'de>,
109 {
110 deserializer.deserialize_newtype_struct(
111 RAW_BSON_NEWTYPE,
112 SeededVisitor {
113 buffer: self.buffer,
114 },
115 )
116 }
117 }
118
119 /// A visitor that builds up a raw BSON value in a single buffer. This visitor will only produce
120 /// valid BSON if the value being deserialized is a byte buffer, slice of bytes, map, or sequence.
121 /// Implementations using this visitor should check the `ElementType` returned from `deserialize` to
122 /// validate that a valid BSON type was visited.
123 impl<'a, 'de> SeededVisitor<'a, 'de> {
124 pub(crate) fn new(buffer: &'a mut CowByteBuffer<'de>) -> Self {
125 Self { buffer }
126 }
127
128 /// Appends a cstring to the buffer. Returns an error if the given string contains a null byte.
129 fn append_cstring(&mut self, key: &str) -> Result<(), String> {
130 let key_bytes = key.as_bytes();
131 if key_bytes.contains(&0) {
132 return Err(format!("key contains interior null byte: {}", key));
133 }
134
135 self.buffer.append_bytes(key_bytes);
136 self.buffer.push_byte(0);
137
138 Ok(())
139 }
140
141 /// Appends a string and its length to the buffer.
142 fn append_string(&mut self, s: &str) {
143 let bytes = s.as_bytes();
144
145 // Add 1 to account for null byte.
146 self.append_length_bytes((bytes.len() + 1) as i32);
147
148 self.buffer.append_bytes(bytes);
149 self.buffer.push_byte(0);
150 }
151
152 /// Converts the given length into little-endian bytes and appends the bytes to the buffer.
153 fn append_length_bytes(&mut self, length: i32) {
154 self.buffer.append_bytes(&length.to_le_bytes());
155 }
156
157 /// Appends an owned byte buffer to the buffer. If the buffer is currently empty (i.e. the byte
158 /// buffer was the top-level value provided to the deserializer), the buffer will be updated to
159 /// contain an owned copy of the bytes provided. Otherwise (i.e. when the value is embedded),
160 /// the bytes and their corresponding length and subtype bytes will be appended to the
161 /// buffer.
162 fn append_owned_binary(&mut self, bytes: Vec<u8>, subtype: u8) {
163 match &mut self.buffer.0 {
164 Some(_) => self.append_embedded_binary(&bytes, subtype),
165 None => self.buffer.0 = Some(Cow::Owned(bytes)),
166 }
167 }
168
169 /// Appends a slice of bytes to the buffer. If the buffer is currently empty (i.e. the byte
170 /// buffer was the top-level value provided to the deserializer), the buffer will be updated to
171 /// contain a reference to the slice of bytes. Otherwise (i.e. when the value is embedded),
172 /// the bytes and their corresponding length and subtype will be appended to the buffer.
173 fn append_borrowed_binary(&mut self, bytes: &'de [u8], subtype: u8) {
174 match &self.buffer.0 {
175 Some(_) => self.append_embedded_binary(bytes, subtype),
176 None => self.buffer.0 = Some(Cow::Borrowed(bytes)),
177 }
178 }
179
180 /// Appends the given bytes and their corresponding length and subtype to the buffer.
181 fn append_embedded_binary(&mut self, bytes: &[u8], subtype: impl Into<u8>) {
182 self.append_length_bytes(bytes.len() as i32);
183 self.buffer.push_byte(subtype.into());
184 self.buffer.append_bytes(bytes);
185 }
186
187 /// Appends 1 byte to the buffer as a placeholder for an element type. This byte should be
188 /// overwritten by a call to append_element after the element has been written to the buffer.
189 fn pad_element_type(&mut self) -> usize {
190 let index = self.buffer.len();
191 self.buffer.push_byte(0);
192 index
193 }
194
195 /// Writes the given element_type at the given index, which should be obtained from
196 /// pad_element_type.
197 fn write_element_type(&mut self, element_type: ElementType, index: usize) {
198 self.buffer
199 .copy_from_slice(index..index + 1, &[element_type as u8]);
200 }
201
202 /// Appends 4 bytes to the buffer as a placeholder for the length of a document. These bytes
203 /// should be overwritten by a call to finish_document after the data in the document has been
204 /// written.
205 fn pad_document_length(&mut self) -> usize {
206 let index = self.buffer.len();
207 self.buffer.append_bytes(&[0; 4]);
208 index
209 }
210
211 /// Writes the length of a document at the given index, which should be obtained from
212 /// pad_document_length, and appends the final null byte of the document. Returns an error if
213 /// the size does not fit into an i32.
214 fn finish_document(&mut self, length_index: usize) -> Result<(), String> {
215 self.buffer.push_byte(0);
216
217 let length_bytes = match i32::try_from(self.buffer.len() - length_index) {
218 Ok(length) => length.to_le_bytes(),
219 Err(_) => return Err("value exceeds maximum length".to_string()),
220 };
221
222 self.buffer
223 .copy_from_slice(length_index..length_index + 4, &length_bytes);
224
225 Ok(())
226 }
227
228 /// Iterates the given `MapAccess` and appends its keys and values to the buffer. The given map
229 /// must have had `next_key` called exactly once, and the value returned from that call must be
230 /// provided as `first_key`. `next_value` must not have been called on the map.
231 pub(crate) fn iterate_map<A>(mut self, first_key: CowStr, mut map: A) -> Result<(), A::Error>
232 where
233 A: MapAccess<'de>,
234 {
235 let length_index = self.pad_document_length();
236
237 let mut current_key = first_key;
238 loop {
239 let element_type_index = self.pad_element_type();
240 self.append_cstring(current_key.0.as_ref())
241 .map_err(SerdeError::custom)?;
242 let element_type = map.next_value_seed(&mut self)?;
243 self.write_element_type(element_type, element_type_index);
244
245 match map.next_key::<CowStr>()? {
246 Some(next_key) => current_key = next_key,
247 None => break,
248 }
249 }
250
251 self.finish_document(length_index)
252 .map_err(SerdeError::custom)?;
253 Ok(())
254 }
255 }
256
257 impl<'a, 'de> Visitor<'de> for SeededVisitor<'a, 'de> {
258 type Value = ElementType;
259
260 fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
261 formatter.write_str("a raw BSON value")
262 }
263
264 fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
265 where
266 D: Deserializer<'de>,
267 {
268 deserializer.deserialize_any(self)
269 }
270
271 fn visit_map<A>(mut self, mut map: A) -> Result<Self::Value, A::Error>
272 where
273 A: MapAccess<'de>,
274 {
275 let first_key = match map.next_key::<CowStr>()? {
276 Some(key) => key,
277 None => {
278 self.buffer
279 .append_bytes(&MIN_BSON_DOCUMENT_SIZE.to_le_bytes());
280 self.buffer.push_byte(0);
281 return Ok(ElementType::EmbeddedDocument);
282 }
283 };
284
285 match first_key.0.as_ref() {
286 "$oid" => {
287 let oid: ObjectId = map.next_value()?;
288 self.buffer.append_bytes(&oid.bytes());
289 Ok(ElementType::ObjectId)
290 }
291 "$symbol" => {
292 let s: &str = map.next_value()?;
293 self.append_string(s);
294 Ok(ElementType::Symbol)
295 }
296 "$numberDecimalBytes" => {
297 let bytes: ByteBuf = map.next_value()?;
298 self.buffer.append_bytes(&bytes.into_vec());
299 Ok(ElementType::Decimal128)
300 }
301 "$regularExpression" => {
302 let regex: BorrowedRegexBody = map.next_value()?;
303 let pattern = regex.pattern.as_ref();
304 let options = regex.options.as_ref();
305
306 self.append_cstring(pattern).map_err(SerdeError::custom)?;
307 self.append_cstring(options).map_err(SerdeError::custom)?;
308
309 Ok(ElementType::RegularExpression)
310 }
311 "$undefined" => {
312 let _: bool = map.next_value()?;
313 Ok(ElementType::Undefined)
314 }
315 "$binary" => {
316 let binary: BorrowedBinaryBody = map.next_value()?;
317 match binary.bytes {
318 Cow::Borrowed(borrowed_bytes) => {
319 self.append_borrowed_binary(borrowed_bytes, binary.subtype);
320 }
321 Cow::Owned(owned_bytes) => {
322 self.append_owned_binary(owned_bytes, binary.subtype);
323 }
324 }
325
326 Ok(ElementType::Binary)
327 }
328 "$date" => {
329 let date: i64 = map.next_value()?;
330 self.buffer.append_bytes(&date.to_le_bytes());
331 Ok(ElementType::DateTime)
332 }
333 "$timestamp" => {
334 let timestamp: TimestampBody = map.next_value()?;
335 self.buffer.append_bytes(&timestamp.i.to_le_bytes());
336 self.buffer.append_bytes(&timestamp.t.to_le_bytes());
337 Ok(ElementType::Timestamp)
338 }
339 "$minKey" => {
340 let _: i32 = map.next_value()?;
341 Ok(ElementType::MinKey)
342 }
343 "$maxKey" => {
344 let _: i32 = map.next_value()?;
345 Ok(ElementType::MaxKey)
346 }
347 "$code" => {
348 let code: CowStr = map.next_value()?;
349 if let Some(key) = map.next_key::<CowStr>()? {
350 let key = key.0.as_ref();
351 if key == "$scope" {
352 let length_index = self.pad_document_length();
353 self.append_string(code.0.as_ref());
354
355 let scope: RawDocumentBuf = map.next_value()?;
356 self.buffer.append_bytes(scope.as_bytes());
357
358 let length_bytes =
359 ((self.buffer.len() - length_index) as i32).to_le_bytes();
360 self.buffer
361 .copy_from_slice(length_index..length_index + 4, &length_bytes);
362
363 Ok(ElementType::JavaScriptCodeWithScope)
364 } else {
365 Err(SerdeError::unknown_field(key, &["$scope"]))
366 }
367 } else {
368 self.append_string(code.0.as_ref());
369 Ok(ElementType::JavaScriptCode)
370 }
371 }
372 "$dbPointer" => {
373 let db_pointer: BorrowedDbPointerBody = map.next_value()?;
374
375 self.append_string(db_pointer.ns.0.as_ref());
376 self.buffer.append_bytes(&db_pointer.id.bytes());
377
378 Ok(ElementType::DbPointer)
379 }
380 RAW_DOCUMENT_NEWTYPE => {
381 let document_bytes: &[u8] = map.next_value()?;
382 self.buffer.append_borrowed_bytes(document_bytes);
383 Ok(ElementType::EmbeddedDocument)
384 }
385 RAW_ARRAY_NEWTYPE => {
386 let array_bytes: &[u8] = map.next_value()?;
387 self.buffer.append_borrowed_bytes(array_bytes);
388 Ok(ElementType::Array)
389 }
390 _ => {
391 self.iterate_map(first_key, map)?;
392 Ok(ElementType::EmbeddedDocument)
393 }
394 }
395 }
396
397 fn visit_seq<A>(mut self, mut seq: A) -> Result<Self::Value, A::Error>
398 where
399 A: SeqAccess<'de>,
400 {
401 let length_index = self.pad_document_length();
402
403 let mut i = 0u32;
404 loop {
405 let element_type_index = self.pad_element_type();
406 let key = i.to_string();
407 self.append_cstring(&key).map_err(SerdeError::custom)?;
408
409 let element_type = match seq.next_element_seed(&mut self)? {
410 Some(element_type) => element_type,
411 None => {
412 // Remove the additional key and padding for the element that was not present.
413 self.buffer.drain(element_type_index..self.buffer.len());
414 break;
415 }
416 };
417
418 self.write_element_type(element_type, element_type_index);
419 i += 1;
420 }
421
422 self.finish_document(length_index)
423 .map_err(SerdeError::custom)?;
424 Ok(ElementType::Array)
425 }
426
427 // visit_string and visit_borrowed_str will forward to this method.
428 fn visit_str<E>(mut self, s: &str) -> Result<Self::Value, E>
429 where
430 E: SerdeError,
431 {
432 self.append_string(s);
433 Ok(ElementType::String)
434 }
435
436 fn visit_bool<E>(self, b: bool) -> Result<Self::Value, E>
437 where
438 E: SerdeError,
439 {
440 self.buffer.push_byte(b as u8);
441 Ok(ElementType::Boolean)
442 }
443
444 fn visit_i8<E>(self, n: i8) -> Result<Self::Value, E>
445 where
446 E: SerdeError,
447 {
448 self.buffer.append_bytes(&(n as i32).to_le_bytes());
449 Ok(ElementType::Int32)
450 }
451
452 fn visit_i16<E>(self, n: i16) -> Result<Self::Value, E>
453 where
454 E: SerdeError,
455 {
456 self.buffer.append_bytes(&(n as i32).to_le_bytes());
457 Ok(ElementType::Int32)
458 }
459
460 fn visit_i32<E>(self, n: i32) -> Result<Self::Value, E>
461 where
462 E: SerdeError,
463 {
464 self.buffer.append_bytes(&n.to_le_bytes());
465 Ok(ElementType::Int32)
466 }
467
468 fn visit_i64<E>(self, n: i64) -> Result<Self::Value, E>
469 where
470 E: SerdeError,
471 {
472 self.buffer.append_bytes(&n.to_le_bytes());
473 Ok(ElementType::Int64)
474 }
475
476 fn visit_u8<E>(self, n: u8) -> Result<Self::Value, E>
477 where
478 E: SerdeError,
479 {
480 self.buffer.append_bytes(&(n as i32).to_le_bytes());
481 Ok(ElementType::Int32)
482 }
483
484 fn visit_u16<E>(self, n: u16) -> Result<Self::Value, E>
485 where
486 E: SerdeError,
487 {
488 self.buffer.append_bytes(&(n as i32).to_le_bytes());
489 Ok(ElementType::Int32)
490 }
491
492 fn visit_u32<E>(self, n: u32) -> Result<Self::Value, E>
493 where
494 E: SerdeError,
495 {
496 match i32::try_from(n) {
497 Ok(n) => {
498 self.buffer.append_bytes(&n.to_le_bytes());
499 Ok(ElementType::Int32)
500 }
501 Err(_) => {
502 self.buffer.append_bytes(&(n as i64).to_le_bytes());
503 Ok(ElementType::Int64)
504 }
505 }
506 }
507
508 fn visit_u64<E>(self, n: u64) -> Result<Self::Value, E>
509 where
510 E: SerdeError,
511 {
512 if let Ok(n) = i32::try_from(n) {
513 self.buffer.append_bytes(&n.to_le_bytes());
514 Ok(ElementType::Int32)
515 } else if let Ok(n) = i64::try_from(n) {
516 self.buffer.append_bytes(&n.to_le_bytes());
517 Ok(ElementType::Int64)
518 } else {
519 Err(SerdeError::custom(format!(
520 "number is too large for BSON: {}",
521 n
522 )))
523 }
524 }
525
526 fn visit_f64<E>(self, n: f64) -> Result<Self::Value, E>
527 where
528 E: SerdeError,
529 {
530 self.buffer.append_bytes(&n.to_le_bytes());
531 Ok(ElementType::Double)
532 }
533
534 fn visit_none<E>(self) -> Result<Self::Value, E>
535 where
536 E: SerdeError,
537 {
538 Ok(ElementType::Null)
539 }
540
541 fn visit_unit<E>(self) -> Result<Self::Value, E>
542 where
543 E: SerdeError,
544 {
545 Ok(ElementType::Null)
546 }
547
548 // visit_byte_buf will forward to this method.
549 fn visit_bytes<E>(mut self, bytes: &[u8]) -> Result<Self::Value, E>
550 where
551 E: SerdeError,
552 {
553 self.append_owned_binary(bytes.to_owned(), BinarySubtype::Generic.into());
554 Ok(ElementType::Binary)
555 }
556
557 fn visit_borrowed_bytes<E>(mut self, bytes: &'de [u8]) -> Result<Self::Value, E>
558 where
559 E: SerdeError,
560 {
561 self.append_borrowed_binary(bytes, BinarySubtype::Generic.into());
562 Ok(ElementType::Binary)
563 }
564 }