Skip to main content

ferroui_remote_protocol/
metsys_bson.rs

1/*
2Copyright (c) 2010, Karl Seguin - http://www.openmymind.net/
3All rights reserved.
4
5Redistribution and use in source and binary forms, with or without
6modification, are permitted provided that the following conditions are met:
7    * Redistributions of source code must retain the above copyright
8      notice, this list of conditions and the following disclaimer.
9    * Redistributions in binary form must reproduce the above copyright
10      notice, this list of conditions and the following disclaimer in the
11      documentation and/or other materials provided with the distribution.
12    * Neither the name of the <organization> nor the
13      names of its contributors may be used to endorse or promote products
14      derived from this software without specific prior written permission.
15
16THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
17ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
20DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26
27Ported to Rust from the C# sources of https://github.com/elaberge/Metsys.Bson
28*/
29
30//! The BSON serializer of the protocol.
31//!
32//! The original finds the properties of a class by reflection. Here a class
33//! states them: [`bson_class!`] lists the properties of a struct in the order
34//! and under the names the original writes them, and [`bson_enum!`] states
35//! that an enumeration is written as its number. From those declarations the
36//! serializer and the deserializer work as the original does: a value is
37//! handed to them in its untyped form ([`ValueRef`] to write, [`Value`] when
38//! read), which is what `object` is in the original, and the declared type of
39//! a property ([`Type`]) decides how an element is read.
40//!
41//! The types of this file are internal to the assembly in the original. They
42//! are public here because the declarations of a message class of another
43//! crate name them.
44
45use std::any::{Any, TypeId};
46use std::collections::HashMap;
47use std::fmt;
48use std::sync::atomic::{AtomicI32, Ordering};
49use std::sync::{Arc, Mutex, OnceLock};
50use std::time::{SystemTime, UNIX_EPOCH};
51
52use crate::error::Error;
53use crate::guid::Guid;
54
55use self::configuration::BsonConfiguration;
56
57/// The element types of BSON, by the byte that precedes an element.
58#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
59#[repr(i32)]
60pub enum Types {
61    Double = 1,
62    String = 2,
63    Object = 3,
64    Array = 4,
65    Binary = 5,
66    Undefined = 6,
67    ObjectId = 7,
68    Boolean = 8,
69    DateTime = 9,
70    Null = 10,
71    Regex = 11,
72    Reference = 12,
73    Code = 13,
74    Symbol = 14,
75    ScopedCode = 15,
76    Int32 = 16,
77    Timestamp = 17,
78    Int64 = 18,
79}
80
81impl Types {
82    /// The member with the given numeric value, if one is defined.
83    pub fn from_value(value: i32) -> Option<Types> {
84        Some(match value {
85            1 => Types::Double,
86            2 => Types::String,
87            3 => Types::Object,
88            4 => Types::Array,
89            5 => Types::Binary,
90            6 => Types::Undefined,
91            7 => Types::ObjectId,
92            8 => Types::Boolean,
93            9 => Types::DateTime,
94            10 => Types::Null,
95            11 => Types::Regex,
96            12 => Types::Reference,
97            13 => Types::Code,
98            14 => Types::Symbol,
99            15 => Types::ScopedCode,
100            16 => Types::Int32,
101            17 => Types::Timestamp,
102            18 => Types::Int64,
103            _ => return None,
104        })
105    }
106}
107
108/// The element type as it was read: `(Types)_reader.ReadByte()` of the
109/// original, which may be a value the enumeration does not define.
110#[derive(Clone, Copy, PartialEq, Eq)]
111struct StoredType(u8);
112
113impl StoredType {
114    fn is(self, types: Types) -> bool {
115        self.0 as i32 == types as i32
116    }
117
118    fn known(self) -> Option<Types> {
119        Types::from_value(self.0 as i32)
120    }
121}
122
123/// `Enum.ToString()`: the name of the member, or the number when there is
124/// none.
125impl fmt::Display for StoredType {
126    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127        match self.known() {
128            Some(types) => write!(f, "{:?}", types),
129            None => write!(f, "{}", self.0),
130        }
131    }
132}
133
134// ---------------------------------------------------------------------------
135// Declarations: what reflection tells the original about a type.
136// ---------------------------------------------------------------------------
137
138/// The declared type of a property, of the items of a collection or of the
139/// root of a document: what the original reads from a `System.Type`, as far
140/// as the serializer distinguishes types.
141#[derive(Clone, Copy, Debug)]
142pub enum Type {
143    /// `object`.
144    Object,
145    /// `string`.
146    String,
147    /// `int`.
148    Int32,
149    /// `long`.
150    Int64,
151    /// `bool`.
152    Boolean,
153    /// `double`.
154    Double,
155    /// `float`.
156    Single,
157    /// `Guid`.
158    Guid,
159    /// `Regex`.
160    Regex,
161    /// `DateTime`.
162    DateTime,
163    /// `byte[]`.
164    ByteArray,
165    /// `ObjectId`.
166    ObjectId,
167    /// `ScopedCode`.
168    ScopedCode,
169    /// An enumeration, with the element type of its underlying type
170    /// ([`Types::Int32`] or [`Types::Int64`]).
171    Enum(Types),
172    /// `Nullable<T>`, and a reference that may be null.
173    Nullable(&'static Type),
174    /// `T[]`.
175    Array(&'static Type),
176    /// `List<T>` and `IList<T>`.
177    List(&'static Type),
178    /// A collection that is not a list (`ICollection<T>`: a set, a queue).
179    Collection(&'static Type),
180    /// The non-generic `IEnumerable` and `IList`.
181    Enumerable,
182    /// `IDictionary<string, T>`.
183    Dictionary(&'static Type),
184    /// A class with declared properties.
185    Class(&'static ClassType),
186}
187
188impl Type {
189    /// `typeof(IEnumerable).IsAssignableFrom(type)` for the types that reach
190    /// the test (a string is handled before it).
191    fn is_enumerable(&self) -> bool {
192        matches!(
193            self,
194            Type::ByteArray
195                | Type::Array(_)
196                | Type::List(_)
197                | Type::Collection(_)
198                | Type::Enumerable
199                | Type::Dictionary(_)
200        )
201    }
202
203    /// `Type.FullName`, for messages.
204    fn full_name(&self) -> String {
205        match self {
206            Type::Class(class) => class.name.to_string(),
207            other => format!("{:?}", other),
208        }
209    }
210}
211
212/// A property of a class, as declared: `PropertyInfo` of the original.
213#[derive(Debug)]
214pub struct PropertyInfo {
215    /// The name of the property, which is its name on the wire unless the
216    /// configuration gives it an alias.
217    pub name: &'static str,
218    /// `PropertyInfo.PropertyType`.
219    pub property_type: &'static Type,
220    /// Whether the property has a `set` accessor. A property without one is
221    /// a container the deserializer fills.
222    pub can_write: bool,
223}
224
225/// A class, as declared: what the original reads from the `System.Type` of
226/// an object. [`bson_class!`] writes one.
227pub struct ClassType {
228    /// `Type.Name`.
229    pub name: &'static str,
230    /// The identity of the Rust type.
231    pub type_id: fn() -> TypeId,
232    /// `Activator.CreateInstance(type, true)`.
233    pub create_instance: fn() -> Box<dyn BsonObject>,
234    /// The properties in the order `Type.GetProperties` returns them: the
235    /// ones the class declares, then the ones of its base classes.
236    pub properties: &'static [PropertyInfo],
237    /// `typeof(IExpando).IsAssignableFrom(type)`.
238    pub is_expando: bool,
239}
240
241impl ClassType {
242    /// The identity of the Rust type: the key of every table over types.
243    pub fn id(&self) -> TypeId {
244        (self.type_id)()
245    }
246}
247
248impl fmt::Debug for ClassType {
249    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250        f.write_str(self.name)
251    }
252}
253
254/// An object of a class with declared properties: what `object` is for the
255/// serializer when it is none of the simple types.
256pub trait BsonObject: Any + Send + Sync + fmt::Debug {
257    /// `object.GetType()`.
258    fn get_type(&self) -> &'static ClassType;
259    /// Reads the property with the given index in [`ClassType::properties`].
260    fn get_property_value(&self, index: usize) -> ValueRef<'_>;
261    /// Assigns the property with the given index. The value is cast to the
262    /// type of the property; one of another type is an `InvalidCastException`.
263    fn set_property_value(&mut self, index: usize, value: Value) -> Result<(), Error>;
264    /// `instance as IExpando`.
265    fn as_expando(&mut self) -> Option<&mut dyn IExpando> {
266        None
267    }
268    /// A copy of the object behind a new handle.
269    fn clone_object(&self) -> Box<dyn BsonObject>;
270    /// Whether the other object is of the same class and has equal
271    /// properties.
272    fn equals(&self, other: &dyn BsonObject) -> bool;
273    fn as_any(&self) -> &dyn Any;
274    fn into_any(self: Box<Self>) -> Box<dyn Any + Send + Sync>;
275}
276
277impl dyn BsonObject {
278    /// `obj is T`.
279    pub fn is<T: Any>(&self) -> bool {
280        self.as_any().is::<T>()
281    }
282
283    /// `obj as T`.
284    pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
285        self.as_any().downcast_ref::<T>()
286    }
287}
288
289impl Clone for Box<dyn BsonObject> {
290    fn clone(&self) -> Self {
291        self.clone_object()
292    }
293}
294
295impl PartialEq for dyn BsonObject {
296    fn eq(&self, other: &Self) -> bool {
297        self.equals(other)
298    }
299}
300
301/// A class that states its properties: `typeof(T)`.
302pub trait BsonClass: BsonObject + Sized {
303    const CLASS: &'static ClassType;
304}
305
306/// A type that a property, an item or a root can have: its declared type and
307/// its conversions to and from the untyped form.
308pub trait BsonValue: Sized {
309    /// `typeof(T)`.
310    const TYPE: Type;
311    /// The value as the serializer receives it: boxing, without a copy.
312    fn as_value(&self) -> ValueRef<'_>;
313    /// The cast of a deserialized value to the type of the property it is
314    /// assigned to. The deserializer does not assign null.
315    fn from_value(value: Value) -> Result<Self, Error>;
316}
317
318/// The `InvalidCastException` of a value that is not of the type of the
319/// property it is assigned to.
320pub fn invalid_cast(value: &Value, expected: &str) -> Error {
321    Error::InvalidCast(format!("Unable to cast object of type '{}' to type '{}'.", value.type_name(), expected))
322}
323
324/// States the properties of a class for the serializer: the counterpart of
325/// the reflection over the properties of a type.
326///
327/// ```ignore
328/// #[derive(Clone, Debug, Default, PartialEq)]
329/// pub struct MeasureViewportMessage { pub width: f64, pub height: f64 }
330///
331/// bson_class!(MeasureViewportMessage as "MeasureViewportMessage" {
332///     "Width" => width: f64,
333///     "Height" => height: f64,
334/// });
335/// ```
336///
337/// Each entry is the name of the property as the original declares it (it is
338/// the name on the wire), the field that holds it (a path for a property of
339/// an embedded base class: `base.x`) and the type of the field. The entries
340/// are in the order `Type.GetProperties` returns the properties: the ones the
341/// class declares, in declaration order, then the ones of its base classes.
342/// The class is `Clone + Debug + Default + PartialEq + Send + Sync`.
343#[macro_export]
344macro_rules! bson_class {
345    ($class:ident as $name:literal { $($property:literal => $($field:ident).+ : $ty:ty),* $(,)? }) => {
346        impl $crate::metsys_bson::BsonClass for $class {
347            const CLASS: &'static $crate::metsys_bson::ClassType = {
348                fn type_id() -> ::std::any::TypeId {
349                    ::std::any::TypeId::of::<$class>()
350                }
351                fn create_instance() -> ::std::boxed::Box<dyn $crate::metsys_bson::BsonObject> {
352                    ::std::boxed::Box::new(<$class as ::std::default::Default>::default())
353                }
354                &$crate::metsys_bson::ClassType {
355                    name: $name,
356                    type_id,
357                    create_instance,
358                    properties: &[$($crate::metsys_bson::PropertyInfo {
359                        name: $property,
360                        property_type: &<$ty as $crate::metsys_bson::BsonValue>::TYPE,
361                        can_write: true,
362                    }),*],
363                    is_expando: false,
364                }
365            };
366        }
367
368        impl $crate::metsys_bson::BsonObject for $class {
369            fn get_type(&self) -> &'static $crate::metsys_bson::ClassType {
370                <$class as $crate::metsys_bson::BsonClass>::CLASS
371            }
372
373            #[allow(unused_mut, unused_assignments, unused_variables)]
374            fn get_property_value(&self, index: usize) -> $crate::metsys_bson::ValueRef<'_> {
375                let mut current = 0usize;
376                $(
377                    if index == current {
378                        return $crate::metsys_bson::BsonValue::as_value(&self.$($field).+);
379                    }
380                    current += 1;
381                )*
382                panic!("{} has no property with the index {}", $name, index)
383            }
384
385            #[allow(unused_mut, unused_assignments, unused_variables)]
386            fn set_property_value(
387                &mut self,
388                index: usize,
389                value: $crate::metsys_bson::Value,
390            ) -> ::std::result::Result<(), $crate::Error> {
391                let mut current = 0usize;
392                $(
393                    if index == current {
394                        self.$($field).+ = <$ty as $crate::metsys_bson::BsonValue>::from_value(value)?;
395                        return ::std::result::Result::Ok(());
396                    }
397                    current += 1;
398                )*
399                panic!("{} has no property with the index {}", $name, index)
400            }
401
402            fn clone_object(&self) -> ::std::boxed::Box<dyn $crate::metsys_bson::BsonObject> {
403                ::std::boxed::Box::new(::std::clone::Clone::clone(self))
404            }
405
406            fn equals(&self, other: &dyn $crate::metsys_bson::BsonObject) -> bool {
407                match other.as_any().downcast_ref::<$class>() {
408                    ::std::option::Option::Some(other) => self == other,
409                    ::std::option::Option::None => false,
410                }
411            }
412
413            fn as_any(&self) -> &dyn ::std::any::Any {
414                self
415            }
416
417            fn into_any(
418                self: ::std::boxed::Box<Self>,
419            ) -> ::std::boxed::Box<dyn ::std::any::Any + ::std::marker::Send + ::std::marker::Sync> {
420                self
421            }
422        }
423
424        impl $crate::metsys_bson::BsonValue for $class {
425            const TYPE: $crate::metsys_bson::Type =
426                $crate::metsys_bson::Type::Class(<$class as $crate::metsys_bson::BsonClass>::CLASS);
427
428            fn as_value(&self) -> $crate::metsys_bson::ValueRef<'_> {
429                $crate::metsys_bson::ValueRef::Object(self)
430            }
431
432            fn from_value(value: $crate::metsys_bson::Value) -> ::std::result::Result<Self, $crate::Error> {
433                match value {
434                    $crate::metsys_bson::Value::Object(object) => {
435                        if object.as_any().is::<$class>() {
436                            match object.into_any().downcast::<$class>() {
437                                ::std::result::Result::Ok(object) => ::std::result::Result::Ok(*object),
438                                ::std::result::Result::Err(_) => ::std::result::Result::Err($crate::Error::InvalidCast(
439                                    ::std::format!("Unable to cast an object to type '{}'.", $name),
440                                )),
441                            }
442                        } else {
443                            ::std::result::Result::Err($crate::metsys_bson::invalid_cast(
444                                &$crate::metsys_bson::Value::Object(object),
445                                $name,
446                            ))
447                        }
448                    }
449                    other => ::std::result::Result::Err($crate::metsys_bson::invalid_cast(&other, $name)),
450                }
451            }
452        }
453    };
454}
455
456/// States that an enumeration is serialized as its number: the counterpart
457/// of `Type.IsEnum` and `Enum.GetUnderlyingType`. The enumeration is
458/// `#[repr(i32)]`, `Copy`, and has `fn from_value(i32) -> Option<Self>`.
459#[macro_export]
460macro_rules! bson_enum {
461    ($enum:ty) => {
462        impl $crate::metsys_bson::BsonValue for $enum {
463            const TYPE: $crate::metsys_bson::Type = $crate::metsys_bson::Type::Enum($crate::metsys_bson::Types::Int32);
464
465            fn as_value(&self) -> $crate::metsys_bson::ValueRef<'_> {
466                $crate::metsys_bson::ValueRef::Enum {
467                    value: *self as i32 as i64,
468                    underlying: $crate::metsys_bson::Types::Int32,
469                }
470            }
471
472            fn from_value(value: $crate::metsys_bson::Value) -> ::std::result::Result<Self, $crate::Error> {
473                match value {
474                    // Deviation (DEVIATIONS.md, Remote protocol): `Enum.Parse` of the
475                    // original accepts a number no member has; a Rust enumeration
476                    // cannot hold one, so it is an error here.
477                    $crate::metsys_bson::Value::Enum { value, .. } => {
478                        match <i32 as ::std::convert::TryFrom<i64>>::try_from(value).ok().and_then(<$enum>::from_value)
479                        {
480                            ::std::option::Option::Some(member) => ::std::result::Result::Ok(member),
481                            ::std::option::Option::None => ::std::result::Result::Err($crate::Error::Argument(
482                                ::std::format!("Requested value '{}' was not found.", value),
483                            )),
484                        }
485                    }
486                    other => ::std::result::Result::Err($crate::metsys_bson::invalid_cast(&other, stringify!($enum))),
487                }
488            }
489        }
490    };
491}
492
493// ---------------------------------------------------------------------------
494// Values: what `object` is for the serializer.
495// ---------------------------------------------------------------------------
496
497/// `RegexOptions`, as far as the serializer reads them.
498#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
499pub struct RegexOptions(pub i32);
500
501#[allow(non_upper_case_globals)]
502impl RegexOptions {
503    pub const None: RegexOptions = RegexOptions(0);
504    pub const IgnoreCase: RegexOptions = RegexOptions(1);
505    pub const Multiline: RegexOptions = RegexOptions(2);
506    pub const ExplicitCapture: RegexOptions = RegexOptions(4);
507    pub const Compiled: RegexOptions = RegexOptions(8);
508    pub const Singleline: RegexOptions = RegexOptions(16);
509    pub const IgnorePatternWhitespace: RegexOptions = RegexOptions(32);
510    pub const RightToLeft: RegexOptions = RegexOptions(64);
511    pub const ECMAScript: RegexOptions = RegexOptions(256);
512    pub const CultureInvariant: RegexOptions = RegexOptions(512);
513
514    /// `(options & flag) == flag`.
515    pub fn contains(self, flag: RegexOptions) -> bool {
516        self.0 & flag.0 == flag.0
517    }
518}
519
520impl std::ops::BitOr for RegexOptions {
521    type Output = RegexOptions;
522
523    fn bitor(self, rhs: RegexOptions) -> RegexOptions {
524        RegexOptions(self.0 | rhs.0)
525    }
526}
527
528/// A regular expression as the serializer sees one: its pattern and its
529/// options. The library does not match with it.
530#[derive(Clone, Debug, Default, PartialEq, Eq)]
531pub struct Regex {
532    pattern: String,
533    options: RegexOptions,
534}
535
536impl Regex {
537    pub fn new(pattern: impl Into<String>, options: RegexOptions) -> Regex {
538        Regex { pattern: pattern.into(), options }
539    }
540
541    /// `Regex.Options`.
542    pub fn options(&self) -> RegexOptions {
543        self.options
544    }
545}
546
547/// `Regex.ToString()`: the pattern.
548impl fmt::Display for Regex {
549    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
550        f.write_str(&self.pattern)
551    }
552}
553
554/// A point in time in UTC, as the serializer sees a `DateTime`: a count of
555/// ticks of 100 nanoseconds from [`Helper::EPOCH`].
556#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
557pub struct DateTime {
558    ticks: i64,
559}
560
561const TICKS_PER_MILLISECOND: i64 = 10_000;
562
563impl DateTime {
564    /// The time the given count of ticks after the epoch (before it when
565    /// negative).
566    pub const fn from_unix_ticks(ticks: i64) -> DateTime {
567        DateTime { ticks }
568    }
569
570    /// `Helper.Epoch.AddMilliseconds(value)`: an `ArgumentOutOfRangeException`
571    /// when the result cannot be represented.
572    pub fn from_unix_milliseconds(milliseconds: i64) -> Result<DateTime, Error> {
573        milliseconds.checked_mul(TICKS_PER_MILLISECOND).map(DateTime::from_unix_ticks).ok_or_else(|| {
574            Error::Argument("The added or subtracted value results in an un-representable DateTime.".to_string())
575        })
576    }
577
578    /// `DateTime.UtcNow`.
579    pub fn utc_now() -> DateTime {
580        DateTime::from(SystemTime::now())
581    }
582
583    /// The ticks from the epoch.
584    pub const fn unix_ticks(&self) -> i64 {
585        self.ticks
586    }
587
588    /// `(long)value.ToUniversalTime().Subtract(Helper.Epoch).TotalMilliseconds`:
589    /// the whole milliseconds from the epoch, truncated towards zero.
590    pub const fn unix_milliseconds(&self) -> i64 {
591        self.ticks / TICKS_PER_MILLISECOND
592    }
593
594    /// `ToString("s", CultureInfo.InvariantCulture)`: `yyyy-MM-ddTHH:mm:ss`.
595    pub fn to_sortable_string(&self) -> String {
596        let seconds = self.ticks.div_euclid(10_000_000);
597        let days = seconds.div_euclid(86_400);
598        let second_of_day = seconds.rem_euclid(86_400);
599        // The civil date of a day count (the algorithm of Howard Hinnant).
600        let z = days + 719_468;
601        let era = z.div_euclid(146_097);
602        let day_of_era = z.rem_euclid(146_097);
603        let year_of_era = (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
604        let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
605        let month_index = (5 * day_of_year + 2) / 153;
606        let day = day_of_year - (153 * month_index + 2) / 5 + 1;
607        let month = if month_index < 10 { month_index + 3 } else { month_index - 9 };
608        let year = year_of_era + era * 400 + if month <= 2 { 1 } else { 0 };
609        format!(
610            "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}",
611            year,
612            month,
613            day,
614            second_of_day / 3_600,
615            second_of_day % 3_600 / 60,
616            second_of_day % 60
617        )
618    }
619}
620
621impl From<SystemTime> for DateTime {
622    fn from(time: SystemTime) -> Self {
623        let ticks = match time.duration_since(UNIX_EPOCH) {
624            Ok(after) => (after.as_nanos() / 100) as i64,
625            Err(before) => -((before.duration().as_nanos() / 100) as i64),
626        };
627        DateTime { ticks }
628    }
629}
630
631/// A dictionary with string keys in insertion order: `IDictionary` as the
632/// serializer writes one, and `Dictionary<string, object>` as it reads one.
633#[derive(Clone, Debug, Default, PartialEq)]
634pub struct Dictionary {
635    entries: Vec<(String, Value)>,
636}
637
638impl Dictionary {
639    pub fn new() -> Dictionary {
640        Dictionary::default()
641    }
642
643    /// `Count`.
644    pub fn len(&self) -> usize {
645        self.entries.len()
646    }
647
648    pub fn is_empty(&self) -> bool {
649        self.entries.is_empty()
650    }
651
652    /// `ContainsKey`.
653    pub fn contains_key(&self, key: &str) -> bool {
654        self.entries.iter().any(|(k, _)| k == key)
655    }
656
657    /// `TryGetValue`.
658    pub fn get(&self, key: &str) -> Option<&Value> {
659        self.entries.iter().find(|(k, _)| k == key).map(|(_, v)| v)
660    }
661
662    /// The indexer's setter: replaces the value of the key or adds the key.
663    pub fn set(&mut self, key: impl Into<String>, value: Value) {
664        let key = key.into();
665        match self.entries.iter_mut().find(|(k, _)| *k == key) {
666            Some(entry) => entry.1 = value,
667            None => self.entries.push((key, value)),
668        }
669    }
670
671    /// `Add`: a key that is already present is an `ArgumentException`.
672    pub fn add(&mut self, key: impl Into<String>, value: Value) -> Result<(), Error> {
673        let key = key.into();
674        if self.contains_key(&key) {
675            return Err(Error::Argument(format!("An item with the same key has already been added. Key: {}", key)));
676        }
677        self.entries.push((key, value));
678        Ok(())
679    }
680
681    /// The keys and their values, in insertion order.
682    pub fn iter(&self) -> impl Iterator<Item = (&str, &Value)> {
683        self.entries.iter().map(|(k, v)| (k.as_str(), v))
684    }
685}
686
687/// A value in its untyped form, owned: what the deserializer produces.
688#[derive(Clone, Debug)]
689pub enum Value {
690    Null,
691    Int32(i32),
692    Int64(i64),
693    Boolean(bool),
694    String(String),
695    Double(f64),
696    Single(f32),
697    Guid(Guid),
698    Regex(Regex),
699    DateTime(DateTime),
700    ByteArray(Vec<u8>),
701    ObjectId(ObjectId),
702    ScopedCode(Box<ScopedCode>),
703    /// A member of an enumeration, as its number and the element type of the
704    /// underlying type.
705    Enum {
706        value: i64,
707        underlying: Types,
708    },
709    Dictionary(Dictionary),
710    /// An array, a list or another collection.
711    Enumerable(Vec<Value>),
712    Object(Box<dyn BsonObject>),
713}
714
715impl Value {
716    pub fn is_null(&self) -> bool {
717        matches!(self, Value::Null)
718    }
719
720    /// The value by reference, as the serializer receives one.
721    pub fn as_ref(&self) -> ValueRef<'_> {
722        match self {
723            Value::Null => ValueRef::Null,
724            Value::Int32(v) => ValueRef::Int32(*v),
725            Value::Int64(v) => ValueRef::Int64(*v),
726            Value::Boolean(v) => ValueRef::Boolean(*v),
727            Value::String(v) => ValueRef::String(v),
728            Value::Double(v) => ValueRef::Double(*v),
729            Value::Single(v) => ValueRef::Single(*v),
730            Value::Guid(v) => ValueRef::Guid(*v),
731            Value::Regex(v) => ValueRef::Regex(v),
732            Value::DateTime(v) => ValueRef::DateTime(*v),
733            Value::ByteArray(v) => ValueRef::ByteArray(v),
734            Value::ObjectId(v) => ValueRef::ObjectId(v),
735            Value::ScopedCode(v) => ValueRef::ScopedCode(v),
736            Value::Enum { value, underlying } => ValueRef::Enum { value: *value, underlying: *underlying },
737            Value::Dictionary(v) => ValueRef::Dictionary(v),
738            Value::Enumerable(v) => ValueRef::Enumerable(v.iter().map(Value::as_ref).collect()),
739            Value::Object(v) => ValueRef::Object(&**v),
740        }
741    }
742
743    /// `value.GetType().Name`, for messages.
744    pub fn type_name(&self) -> &'static str {
745        match self {
746            Value::Null => "null",
747            Value::Int32(_) => "Int32",
748            Value::Int64(_) => "Int64",
749            Value::Boolean(_) => "Boolean",
750            Value::String(_) => "String",
751            Value::Double(_) => "Double",
752            Value::Single(_) => "Single",
753            Value::Guid(_) => "Guid",
754            Value::Regex(_) => "Regex",
755            Value::DateTime(_) => "DateTime",
756            Value::ByteArray(_) => "Byte[]",
757            Value::ObjectId(_) => "ObjectId",
758            Value::ScopedCode(_) => "ScopedCode",
759            Value::Enum { .. } => "Enum",
760            Value::Dictionary(_) => "Dictionary`2",
761            Value::Enumerable(_) => "List`1",
762            Value::Object(object) => object.get_type().name,
763        }
764    }
765}
766
767impl PartialEq for Value {
768    fn eq(&self, other: &Self) -> bool {
769        match (self, other) {
770            (Value::Null, Value::Null) => true,
771            (Value::Int32(a), Value::Int32(b)) => a == b,
772            (Value::Int64(a), Value::Int64(b)) => a == b,
773            (Value::Boolean(a), Value::Boolean(b)) => a == b,
774            (Value::String(a), Value::String(b)) => a == b,
775            (Value::Double(a), Value::Double(b)) => a == b,
776            (Value::Single(a), Value::Single(b)) => a == b,
777            (Value::Guid(a), Value::Guid(b)) => a == b,
778            (Value::Regex(a), Value::Regex(b)) => a == b,
779            (Value::DateTime(a), Value::DateTime(b)) => a == b,
780            (Value::ByteArray(a), Value::ByteArray(b)) => a == b,
781            (Value::ObjectId(a), Value::ObjectId(b)) => a == b,
782            (Value::ScopedCode(a), Value::ScopedCode(b)) => a == b,
783            (Value::Enum { value: a, underlying: x }, Value::Enum { value: b, underlying: y }) => a == b && x == y,
784            (Value::Dictionary(a), Value::Dictionary(b)) => a == b,
785            (Value::Enumerable(a), Value::Enumerable(b)) => a == b,
786            (Value::Object(a), Value::Object(b)) => a.equals(&**b),
787            _ => false,
788        }
789    }
790}
791
792/// A value in its untyped form, borrowed: what the serializer is given, so
793/// that writing an object copies none of its strings, arrays or objects.
794#[derive(Clone, Debug)]
795pub enum ValueRef<'a> {
796    Null,
797    Int32(i32),
798    Int64(i64),
799    Boolean(bool),
800    String(&'a str),
801    Double(f64),
802    Single(f32),
803    Guid(Guid),
804    Regex(&'a Regex),
805    DateTime(DateTime),
806    ByteArray(&'a [u8]),
807    ObjectId(&'a ObjectId),
808    ScopedCode(&'a ScopedCode),
809    Enum { value: i64, underlying: Types },
810    Dictionary(&'a Dictionary),
811    Enumerable(Vec<ValueRef<'a>>),
812    Object(&'a dyn BsonObject),
813}
814
815impl ValueRef<'_> {
816    pub fn is_null(&self) -> bool {
817        matches!(self, ValueRef::Null)
818    }
819
820    /// A copy of the value that owns what it refers to.
821    pub fn to_value(&self) -> Value {
822        match self {
823            ValueRef::Null => Value::Null,
824            ValueRef::Int32(v) => Value::Int32(*v),
825            ValueRef::Int64(v) => Value::Int64(*v),
826            ValueRef::Boolean(v) => Value::Boolean(*v),
827            ValueRef::String(v) => Value::String((*v).to_string()),
828            ValueRef::Double(v) => Value::Double(*v),
829            ValueRef::Single(v) => Value::Single(*v),
830            ValueRef::Guid(v) => Value::Guid(*v),
831            ValueRef::Regex(v) => Value::Regex((*v).clone()),
832            ValueRef::DateTime(v) => Value::DateTime(*v),
833            ValueRef::ByteArray(v) => Value::ByteArray(v.to_vec()),
834            ValueRef::ObjectId(v) => Value::ObjectId((*v).clone()),
835            ValueRef::ScopedCode(v) => Value::ScopedCode(Box::new((*v).clone())),
836            ValueRef::Enum { value, underlying } => Value::Enum { value: *value, underlying: *underlying },
837            ValueRef::Dictionary(v) => Value::Dictionary((*v).clone()),
838            ValueRef::Enumerable(v) => Value::Enumerable(v.iter().map(ValueRef::to_value).collect()),
839            ValueRef::Object(v) => Value::Object(v.clone_object()),
840        }
841    }
842}
843
844macro_rules! bson_simple_value {
845    ($ty:ty, $type:ident, $name:literal, |$this:ident| $as_value:expr, $variant:ident) => {
846        impl BsonValue for $ty {
847            const TYPE: Type = Type::$type;
848
849            fn as_value(&self) -> ValueRef<'_> {
850                let $this = self;
851                $as_value
852            }
853
854            fn from_value(value: Value) -> Result<Self, Error> {
855                match value {
856                    Value::$variant(value) => Ok(value),
857                    other => Err(invalid_cast(&other, $name)),
858                }
859            }
860        }
861    };
862}
863
864bson_simple_value!(i32, Int32, "Int32", |v| ValueRef::Int32(*v), Int32);
865bson_simple_value!(i64, Int64, "Int64", |v| ValueRef::Int64(*v), Int64);
866bson_simple_value!(bool, Boolean, "Boolean", |v| ValueRef::Boolean(*v), Boolean);
867bson_simple_value!(String, String, "String", |v| ValueRef::String(v), String);
868bson_simple_value!(f64, Double, "Double", |v| ValueRef::Double(*v), Double);
869bson_simple_value!(f32, Single, "Single", |v| ValueRef::Single(*v), Single);
870bson_simple_value!(Guid, Guid, "Guid", |v| ValueRef::Guid(*v), Guid);
871bson_simple_value!(Regex, Regex, "Regex", |v| ValueRef::Regex(v), Regex);
872bson_simple_value!(DateTime, DateTime, "DateTime", |v| ValueRef::DateTime(*v), DateTime);
873bson_simple_value!(Vec<u8>, ByteArray, "Byte[]", |v| ValueRef::ByteArray(v), ByteArray);
874bson_simple_value!(ObjectId, ObjectId, "ObjectId", |v| ValueRef::ObjectId(v), ObjectId);
875
876impl BsonValue for ScopedCode {
877    const TYPE: Type = Type::ScopedCode;
878
879    fn as_value(&self) -> ValueRef<'_> {
880        ValueRef::ScopedCode(self)
881    }
882
883    fn from_value(value: Value) -> Result<Self, Error> {
884        match value {
885            Value::ScopedCode(value) => Ok(*value),
886            other => Err(invalid_cast(&other, "ScopedCode")),
887        }
888    }
889}
890
891/// `object`: any value.
892impl BsonValue for Value {
893    const TYPE: Type = Type::Object;
894
895    fn as_value(&self) -> ValueRef<'_> {
896        self.as_ref()
897    }
898
899    fn from_value(value: Value) -> Result<Self, Error> {
900        Ok(value)
901    }
902}
903
904/// `IDictionary<string, object>`.
905impl BsonValue for Dictionary {
906    const TYPE: Type = Type::Dictionary(&Type::Object);
907
908    fn as_value(&self) -> ValueRef<'_> {
909        ValueRef::Dictionary(self)
910    }
911
912    fn from_value(value: Value) -> Result<Self, Error> {
913        match value {
914            Value::Dictionary(value) => Ok(value),
915            other => Err(invalid_cast(&other, "Dictionary`2")),
916        }
917    }
918}
919
920/// `T[]`. (`byte[]` is `Vec<u8>`, which is written as binary data.)
921impl<T: BsonValue> BsonValue for Vec<T> {
922    const TYPE: Type = Type::Array(&T::TYPE);
923
924    fn as_value(&self) -> ValueRef<'_> {
925        ValueRef::Enumerable(self.iter().map(T::as_value).collect())
926    }
927
928    fn from_value(value: Value) -> Result<Self, Error> {
929        match value {
930            Value::Enumerable(items) => items.into_iter().map(T::from_value).collect(),
931            other => Err(invalid_cast(&other, "Array")),
932        }
933    }
934}
935
936/// `Nullable<T>`, and a reference that may be null.
937impl<T: BsonValue> BsonValue for Option<T> {
938    const TYPE: Type = Type::Nullable(&T::TYPE);
939
940    fn as_value(&self) -> ValueRef<'_> {
941        match self {
942            Some(value) => value.as_value(),
943            None => ValueRef::Null,
944        }
945    }
946
947    fn from_value(value: Value) -> Result<Self, Error> {
948        match value {
949            Value::Null => Ok(None),
950            value => T::from_value(value).map(Some),
951        }
952    }
953}
954
955// ---------------------------------------------------------------------------
956// Serializer
957// ---------------------------------------------------------------------------
958
959pub struct Serializer {
960    writer: Vec<u8>,
961    current: Option<Box<Document>>,
962}
963
964impl Serializer {
965    /// `_typeMap`: the element type of a simple value. `None` for a value
966    /// that "isn't a simple type".
967    fn type_map(value: &ValueRef<'_>) -> Option<Types> {
968        match value {
969            ValueRef::Int32(_) => Some(Types::Int32),
970            ValueRef::Int64(_) => Some(Types::Int64),
971            ValueRef::Boolean(_) => Some(Types::Boolean),
972            ValueRef::String(_) => Some(Types::String),
973            ValueRef::Double(_) => Some(Types::Double),
974            ValueRef::Guid(_) => Some(Types::Binary),
975            ValueRef::Regex(_) => Some(Types::Regex),
976            ValueRef::DateTime(_) => Some(Types::DateTime),
977            ValueRef::Single(_) => Some(Types::Double),
978            ValueRef::ByteArray(_) => Some(Types::Binary),
979            ValueRef::ObjectId(_) => Some(Types::ObjectId),
980            ValueRef::ScopedCode(_) => Some(Types::ScopedCode),
981            // `if (type.IsEnum) type = Enum.GetUnderlyingType(type)`.
982            ValueRef::Enum { underlying: Types::Int32, .. } => Some(Types::Int32),
983            ValueRef::Enum { underlying: Types::Int64, .. } => Some(Types::Int64),
984            _ => None,
985        }
986    }
987
988    /// `Serialize<T>(T document)`.
989    pub fn serialize<T: BsonValue>(document: &T) -> Result<Vec<u8>, Error> {
990        Serializer::serialize_object(document.as_value())
991    }
992
993    /// `Serialize(object document)`.
994    pub fn serialize_object(document: ValueRef<'_>) -> Result<Vec<u8>, Error> {
995        match document {
996            // `document.GetType()` of null.
997            ValueRef::Null => return Err(Error::NullReference),
998            ValueRef::Object(_) | ValueRef::Dictionary(_) => {}
999            // A value type, or an enumerable that is not a dictionary. A
1000            // regular expression, an object identifier and scoped code pass
1001            // the test of the original, which then writes their properties by
1002            // reflection; the port has no declaration of them as classes and
1003            // rejects them as it rejects the other values.
1004            _ => return Err(BsonException::with_message("Root type must be an object").into()),
1005        }
1006        let mut serializer = Serializer::new(Vec::with_capacity(250));
1007        serializer.write_document(&document)?;
1008        Ok(serializer.writer)
1009    }
1010
1011    fn new(writer: Vec<u8>) -> Serializer {
1012        Serializer { writer, current: None }
1013    }
1014
1015    fn new_document(&mut self) {
1016        let old = self.current.take();
1017        self.current = Some(Box::new(Document { parent: old, length: self.writer.len() as i32, digested: 4 }));
1018        self.writer.extend_from_slice(&0i32.to_le_bytes()); // length placeholder
1019    }
1020
1021    fn end_document(&mut self, include_eeo: bool) {
1022        if include_eeo {
1023            self.written(1);
1024            self.writer.push(0);
1025        }
1026
1027        let old = *self.current.take().expect("end_document without a document");
1028        let at = old.length as usize;
1029        self.writer[at..at + 4].copy_from_slice(&old.digested.to_le_bytes()); // override the document length placeholder
1030        self.current = old.parent;
1031        if self.current.is_some() {
1032            self.written(old.digested);
1033        }
1034    }
1035
1036    fn written(&mut self, length: i32) {
1037        self.current.as_mut().expect("written without a document").digested += length;
1038    }
1039
1040    fn write_document(&mut self, document: &ValueRef<'_>) -> Result<(), Error> {
1041        self.new_document();
1042        self.write_object(document)?;
1043        self.end_document(true);
1044        Ok(())
1045    }
1046
1047    fn write_object(&mut self, document: &ValueRef<'_>) -> Result<(), Error> {
1048        let object = match document {
1049            ValueRef::Dictionary(dictionary) => return self.write_dictionary(dictionary),
1050            ValueRef::Object(object) => *object,
1051            // `document.GetType()` of null.
1052            ValueRef::Null => return Err(Error::NullReference),
1053            // A value that is neither: the original reflects over its
1054            // properties; the simple values have none that it could write.
1055            _ => return Ok(()),
1056        };
1057
1058        let type_helper = TypeHelper::get_helper_for_type(object.get_type());
1059        for property in type_helper.get_properties() {
1060            if property.ignored() {
1061                continue;
1062            }
1063            let name = property.name();
1064            let value = property.getter(object);
1065            if value.is_null() && property.ignored_if_null() {
1066                continue;
1067            }
1068            self.serialize_member(name, &value)?;
1069        }
1070        Ok(())
1071    }
1072
1073    fn serialize_member(&mut self, name: &str, value: &ValueRef<'_>) -> Result<(), Error> {
1074        if value.is_null() {
1075            self.write_type(Types::Null);
1076            self.write_name(name);
1077            return Ok(());
1078        }
1079
1080        let storage_type = match Serializer::type_map(value) {
1081            Some(storage_type) => storage_type,
1082            None => {
1083                // this isn't a simple type;
1084                return self.write_named(name, value);
1085            }
1086        };
1087
1088        self.write_type(storage_type);
1089        self.write_name(name);
1090        match value {
1091            ValueRef::Int32(value) => {
1092                self.written(4);
1093                self.writer.extend_from_slice(&value.to_le_bytes());
1094            }
1095            ValueRef::Int64(value) => {
1096                self.written(8);
1097                self.writer.extend_from_slice(&value.to_le_bytes());
1098            }
1099            // `(int)value` and `(long)value` of a boxed member of an enumeration.
1100            ValueRef::Enum { value, underlying } => {
1101                if *underlying == Types::Int32 {
1102                    self.written(4);
1103                    self.writer.extend_from_slice(&(*value as i32).to_le_bytes());
1104                } else {
1105                    self.written(8);
1106                    self.writer.extend_from_slice(&value.to_le_bytes());
1107                }
1108            }
1109            ValueRef::String(value) => self.write_string(value),
1110            ValueRef::Single(value) => {
1111                self.written(8);
1112                self.writer.extend_from_slice(&(*value as f64).to_le_bytes());
1113            }
1114            ValueRef::Double(value) => {
1115                self.written(8);
1116                self.writer.extend_from_slice(&value.to_le_bytes());
1117            }
1118            ValueRef::Boolean(value) => {
1119                self.written(1);
1120                self.writer.push(if *value { 1 } else { 0 });
1121            }
1122            ValueRef::DateTime(value) => {
1123                self.written(8);
1124                self.writer.extend_from_slice(&value.unix_milliseconds().to_le_bytes());
1125            }
1126            ValueRef::ByteArray(_) | ValueRef::Guid(_) => self.write_binary(value),
1127            ValueRef::ScopedCode(value) => self.write_scoped_code(value)?,
1128            ValueRef::ObjectId(value) => {
1129                let bytes = value.value().ok_or(Error::NullReference)?;
1130                self.written(bytes.len() as i32);
1131                self.writer.extend_from_slice(bytes);
1132            }
1133            ValueRef::Regex(value) => self.write_regex(value),
1134            ValueRef::Null | ValueRef::Dictionary(_) | ValueRef::Enumerable(_) | ValueRef::Object(_) => {
1135                unreachable!("not a simple type")
1136            }
1137        }
1138        Ok(())
1139    }
1140
1141    /// `Write(string name, object value)`.
1142    fn write_named(&mut self, name: &str, value: &ValueRef<'_>) -> Result<(), Error> {
1143        match value {
1144            ValueRef::Dictionary(dictionary) => {
1145                self.write_type(Types::Object);
1146                self.write_name(name);
1147                self.new_document();
1148                self.write_dictionary(dictionary)?;
1149                self.end_document(true);
1150            }
1151            ValueRef::Enumerable(enumerable) => {
1152                self.write_type(Types::Array);
1153                self.write_name(name);
1154                self.new_document();
1155                self.write_enumerable(enumerable)?;
1156                self.end_document(true);
1157            }
1158            _ => {
1159                self.write_type(Types::Object);
1160                self.write_name(name);
1161                self.write_document(value)?; // Write manages new/end document
1162            }
1163        }
1164        Ok(())
1165    }
1166
1167    /// `Write(IEnumerable enumerable)`.
1168    fn write_enumerable(&mut self, enumerable: &[ValueRef<'_>]) -> Result<(), Error> {
1169        for (index, value) in enumerable.iter().enumerate() {
1170            self.serialize_member(&index.to_string(), value)?;
1171        }
1172        Ok(())
1173    }
1174
1175    /// `Write(IDictionary dictionary)`.
1176    fn write_dictionary(&mut self, dictionary: &Dictionary) -> Result<(), Error> {
1177        for (key, value) in dictionary.iter() {
1178            self.serialize_member(key, &value.as_ref())?;
1179        }
1180        Ok(())
1181    }
1182
1183    fn write_binary(&mut self, value: &ValueRef<'_>) {
1184        match value {
1185            ValueRef::ByteArray(bytes) => {
1186                let length = bytes.len() as i32;
1187                self.writer.extend_from_slice(&(length + 4).to_le_bytes());
1188                self.writer.push(2);
1189                self.writer.extend_from_slice(&length.to_le_bytes());
1190                self.writer.extend_from_slice(bytes);
1191                self.written(9 + length);
1192            }
1193            ValueRef::Guid(guid) => {
1194                let bytes = guid.to_byte_array();
1195                self.writer.extend_from_slice(&(bytes.len() as i32).to_le_bytes());
1196                self.writer.push(3);
1197                self.writer.extend_from_slice(&bytes);
1198                self.written(5 + bytes.len() as i32);
1199            }
1200            _ => {}
1201        }
1202    }
1203
1204    /// `Write(Types type)`.
1205    fn write_type(&mut self, types: Types) {
1206        self.writer.push(types as i32 as u8);
1207        self.written(1);
1208    }
1209
1210    fn write_name(&mut self, name: &str) {
1211        let bytes = name.as_bytes();
1212        self.writer.extend_from_slice(bytes);
1213        self.writer.push(0);
1214        self.written(bytes.len() as i32 + 1);
1215    }
1216
1217    /// `Write(string name)`: a string value.
1218    fn write_string(&mut self, name: &str) {
1219        let bytes = name.as_bytes();
1220        self.writer.extend_from_slice(&(bytes.len() as i32 + 1).to_le_bytes());
1221        self.writer.extend_from_slice(bytes);
1222        self.writer.push(0);
1223        self.written(bytes.len() as i32 + 5); // stringLength + length + null byte
1224    }
1225
1226    /// `Write(Regex regex)`.
1227    fn write_regex(&mut self, regex: &Regex) {
1228        self.write_name(&regex.to_string());
1229
1230        let mut options = String::new();
1231        if regex.options().contains(RegexOptions::ECMAScript) {
1232            options.push('e');
1233        }
1234
1235        if regex.options().contains(RegexOptions::IgnoreCase) {
1236            options.push('i');
1237        }
1238
1239        if regex.options().contains(RegexOptions::CultureInvariant) {
1240            options.push('l');
1241        }
1242
1243        if regex.options().contains(RegexOptions::Multiline) {
1244            options.push('m');
1245        }
1246
1247        if regex.options().contains(RegexOptions::Singleline) {
1248            options.push('s');
1249        }
1250
1251        options.push('u'); // all .net regex are unicode regex, therefore:
1252        if regex.options().contains(RegexOptions::IgnorePatternWhitespace) {
1253            options.push('w');
1254        }
1255
1256        if regex.options().contains(RegexOptions::ExplicitCapture) {
1257            options.push('x');
1258        }
1259
1260        self.write_name(&options);
1261    }
1262
1263    /// `Write(ScopedCode value)`.
1264    fn write_scoped_code(&mut self, value: &ScopedCode) -> Result<(), Error> {
1265        self.new_document();
1266        self.write_string(value.code_string.as_deref().ok_or(Error::NullReference)?);
1267        self.write_document(&value.scope.as_ref())?;
1268        self.end_document(false);
1269        Ok(())
1270    }
1271}
1272
1273/// Code with the scope it runs in. The original has a second, generic class
1274/// whose scope is typed; a scope here is a [`Value`], which holds an object
1275/// of any class, so the one struct serves both.
1276#[derive(Clone, Debug, PartialEq)]
1277pub struct ScopedCode {
1278    pub code_string: Option<String>,
1279    pub scope: Value,
1280}
1281
1282impl Default for ScopedCode {
1283    fn default() -> Self {
1284        ScopedCode { code_string: None, scope: Value::Null }
1285    }
1286}
1287
1288pub struct ObjectIdGenerator;
1289
1290static COUNTER: AtomicI32 = AtomicI32::new(0);
1291
1292impl ObjectIdGenerator {
1293    pub fn generate() -> Vec<u8> {
1294        let mut oid = vec![0u8; 12];
1295        let mut copyidx = 0;
1296
1297        oid[copyidx..copyidx + 4].copy_from_slice(&ObjectIdGenerator::generate_time().to_le_bytes());
1298        copyidx += 4;
1299
1300        oid[copyidx..copyidx + 3].copy_from_slice(&ObjectIdGenerator::machine_hash()[0..3]);
1301        copyidx += 3;
1302
1303        oid[copyidx..copyidx + 2].copy_from_slice(&ObjectIdGenerator::generate_proc_id().to_le_bytes()[0..2]);
1304        copyidx += 2;
1305
1306        oid[copyidx..copyidx + 3].copy_from_slice(&ObjectIdGenerator::generate_inc().to_le_bytes()[0..3]);
1307        oid
1308    }
1309
1310    /// The milliseconds of the current time of day in UTC: the original
1311    /// builds a time on the day of the epoch from the hour, minute, second
1312    /// and millisecond of now.
1313    fn generate_time() -> i32 {
1314        let now = DateTime::utc_now();
1315        let milliseconds = now.unix_ticks().div_euclid(TICKS_PER_MILLISECOND);
1316        milliseconds.rem_euclid(86_400_000) as i32
1317    }
1318
1319    fn generate_inc() -> i32 {
1320        COUNTER.fetch_add(1, Ordering::SeqCst)
1321    }
1322
1323    fn machine_hash() -> &'static [u8; 8] {
1324        static MACHINE_HASH: OnceLock<[u8; 8]> = OnceLock::new();
1325        MACHINE_HASH.get_or_init(ObjectIdGenerator::generate_host_hash)
1326    }
1327
1328    // Deviation (DEVIATIONS.md, Remote protocol): the original hashes
1329    // `Dns.GetHostName()` with MD5. The standard library has neither, so the
1330    // name comes from the environment and the hash is the one of the standard
1331    // library. The three bytes only tell machines apart.
1332    fn generate_host_hash() -> [u8; 8] {
1333        use std::hash::{Hash, Hasher};
1334
1335        let host = std::env::var("HOSTNAME").or_else(|_| std::env::var("COMPUTERNAME")).unwrap_or_default();
1336        let mut hasher = std::collections::hash_map::DefaultHasher::new();
1337        host.hash(&mut hasher);
1338        hasher.finish().to_le_bytes()
1339    }
1340
1341    fn generate_proc_id() -> i32 {
1342        std::process::id() as i32
1343    }
1344}
1345
1346#[derive(Clone, Debug, Default)]
1347pub struct ObjectId {
1348    value: Option<Vec<u8>>,
1349}
1350
1351impl ObjectId {
1352    /// `new ObjectId()`: an identifier without a value.
1353    pub fn new() -> ObjectId {
1354        ObjectId::default()
1355    }
1356
1357    /// `new ObjectId(string value)`.
1358    pub fn from_string(value: &str) -> Result<ObjectId, Error> {
1359        Ok(ObjectId::from_bytes(ObjectId::decode_hex(value)?))
1360    }
1361
1362    /// `new ObjectId(byte[] value)`.
1363    pub fn from_bytes(value: Vec<u8>) -> ObjectId {
1364        ObjectId { value: Some(value) }
1365    }
1366
1367    pub fn empty() -> ObjectId {
1368        ObjectId::from_bytes(vec![0; 12])
1369    }
1370
1371    pub fn value(&self) -> Option<&[u8]> {
1372        self.value.as_deref()
1373    }
1374
1375    pub fn new_object_id() -> ObjectId {
1376        // TODO: generate random-ish bits.
1377        ObjectId { value: Some(ObjectIdGenerator::generate()) }
1378    }
1379
1380    /// `TryParse(string value, out ObjectId id)`: `None` where the original
1381    /// returns false (and hands out the empty identifier).
1382    pub fn try_parse(value: Option<&str>) -> Option<ObjectId> {
1383        let value = value?;
1384        if value.chars().count() != 24 {
1385            return None;
1386        }
1387
1388        match ObjectId::from_string(value) {
1389            Ok(id) => Some(id),
1390            Err(Error::Format(_)) => None,
1391            Err(_) => None,
1392        }
1393    }
1394
1395    /// `DecodeHex`: `Convert.ToByte(pair, 16)` for every two characters.
1396    pub fn decode_hex(val: &str) -> Result<Vec<u8>, Error> {
1397        let chars: Vec<char> = val.chars().collect();
1398        let number_chars = chars.len();
1399        let mut bytes = vec![0u8; number_chars / 2];
1400
1401        let mut i = 0;
1402        while i < number_chars {
1403            if i + 2 > number_chars {
1404                // `new string(chars, i, 2)` past the end of the array.
1405                return Err(Error::Argument(
1406                    "Index and length must refer to a location within the string.".to_string(),
1407                ));
1408            }
1409            let pair: String = chars[i..i + 2].iter().collect();
1410            if !pair.chars().all(|c| c.is_ascii_hexdigit()) {
1411                return Err(Error::Format("Could not find any recognizable digits.".to_string()));
1412            }
1413            bytes[i / 2] = u8::from_str_radix(&pair, 16)
1414                .map_err(|_| Error::Format("Could not find any recognizable digits.".to_string()))?;
1415            i += 2;
1416        }
1417
1418        Ok(bytes)
1419    }
1420
1421    /// The text of the value, `None` without one: what `ToString()` returns.
1422    fn to_option_string(&self) -> Option<String> {
1423        self.value.as_ref().map(|value| value.iter().map(|b| format!("{:02x}", b)).collect())
1424    }
1425}
1426
1427/// `operator ==`, `operator !=` and `Equals`: by the text of the value.
1428impl PartialEq for ObjectId {
1429    fn eq(&self, other: &Self) -> bool {
1430        self.to_option_string() == other.to_option_string()
1431    }
1432}
1433
1434impl Eq for ObjectId {}
1435
1436/// `GetHashCode`: of the text of the value.
1437impl std::hash::Hash for ObjectId {
1438    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1439        self.to_option_string().hash(state);
1440    }
1441}
1442
1443/// `ToString()`: the value in lower-case hexadecimal digits; nothing for an
1444/// identifier without a value (the original returns null).
1445impl fmt::Display for ObjectId {
1446    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1447        match self.to_option_string() {
1448            Some(text) => f.write_str(&text),
1449            None => Ok(()),
1450        }
1451    }
1452}
1453
1454/// `implicit operator string(ObjectId oid)`.
1455impl From<&ObjectId> for Option<String> {
1456    fn from(oid: &ObjectId) -> Self {
1457        oid.to_option_string()
1458    }
1459}
1460
1461/// `implicit operator ObjectId(string oidString)`.
1462impl TryFrom<&str> for ObjectId {
1463    type Error = Error;
1464
1465    fn try_from(oid_string: &str) -> Result<Self, Self::Error> {
1466        ObjectId::from_string(oid_string)
1467    }
1468}
1469
1470/// A class that keeps the members a document has and the class does not.
1471pub trait IExpando {
1472    fn expando(&mut self) -> &mut Dictionary;
1473}
1474
1475/// A property of a class as the serializer uses it: under its alias, with
1476/// what the configuration says about it.
1477#[derive(Clone, Debug)]
1478pub struct MagicProperty {
1479    property: &'static PropertyInfo,
1480    index: usize,
1481    name: String,
1482    ignored: bool,
1483    ignored_if_null: bool,
1484}
1485
1486impl MagicProperty {
1487    pub fn new(
1488        property: &'static PropertyInfo,
1489        index: usize,
1490        name: String,
1491        ignored: bool,
1492        ignored_if_null: bool,
1493    ) -> Self {
1494        MagicProperty { property, index, name, ignored, ignored_if_null }
1495    }
1496
1497    /// `Type`: the declared type of the property.
1498    pub fn property_type(&self) -> &'static Type {
1499        self.property.property_type
1500    }
1501
1502    pub fn name(&self) -> &str {
1503        &self.name
1504    }
1505
1506    pub fn ignored(&self) -> bool {
1507        self.ignored
1508    }
1509
1510    pub fn ignored_if_null(&self) -> bool {
1511        self.ignored_if_null
1512    }
1513
1514    /// `Setter != null`: whether the property has a `set` accessor.
1515    pub fn has_setter(&self) -> bool {
1516        self.property.can_write
1517    }
1518
1519    /// `Setter(instance, value)`.
1520    pub fn setter(&self, instance: &mut dyn BsonObject, value: Value) -> Result<(), Error> {
1521        instance.set_property_value(self.index, value)
1522    }
1523
1524    /// `Getter(instance)`.
1525    pub fn getter<'a>(&self, instance: &'a dyn BsonObject) -> ValueRef<'a> {
1526        instance.get_property_value(self.index)
1527    }
1528}
1529
1530/// `StringComparer.CurrentCultureIgnoreCase` of the property table. The port
1531/// compares the lower-case forms of the characters.
1532fn equals_ignore_case(a: &str, b: &str) -> bool {
1533    a.chars().flat_map(char::to_lowercase).eq(b.chars().flat_map(char::to_lowercase))
1534}
1535
1536pub struct TypeHelper {
1537    properties: Vec<MagicProperty>,
1538    expando: Option<MagicProperty>,
1539}
1540
1541impl TypeHelper {
1542    fn new(class: &'static ClassType) -> TypeHelper {
1543        let properties = TypeHelper::load_magic_properties(class, class.properties);
1544        let mut expando = None;
1545        if class.is_expando {
1546            expando = Some(
1547                properties
1548                    .iter()
1549                    .find(|p| equals_ignore_case(p.name(), "Expando"))
1550                    .unwrap_or_else(|| panic!("The given key 'Expando' was not present in the dictionary."))
1551                    .clone(),
1552            );
1553        }
1554        TypeHelper { properties, expando }
1555    }
1556
1557    pub fn expando(&self) -> Option<&MagicProperty> {
1558        self.expando.as_ref()
1559    }
1560
1561    pub fn get_properties(&self) -> &[MagicProperty] {
1562        &self.properties
1563    }
1564
1565    /// `FindProperty(string name)`: without regard to case.
1566    pub fn find_property(&self, name: &str) -> Option<&MagicProperty> {
1567        self.properties.iter().find(|p| equals_ignore_case(p.name(), name))
1568    }
1569
1570    pub fn get_helper_for_type(class: &'static ClassType) -> Arc<TypeHelper> {
1571        static CACHED_TYPE_LOOKUP: OnceLock<Mutex<HashMap<TypeId, Arc<TypeHelper>>>> = OnceLock::new();
1572        let mut cache = CACHED_TYPE_LOOKUP.get_or_init(Default::default).lock().unwrap();
1573        cache.entry(class.id()).or_insert_with(|| Arc::new(TypeHelper::new(class))).clone()
1574    }
1575
1576    /// `FindProperty(Type type, string name)`: the declared property with
1577    /// exactly that name. The original throws when there is none (`First()`).
1578    pub fn find_property_info(class: &'static ClassType, name: &str) -> Result<&'static PropertyInfo, Error> {
1579        class
1580            .properties
1581            .iter()
1582            .find(|p| p.name == name)
1583            .ok_or_else(|| Error::InvalidOperation("Sequence contains no matching element".to_string()))
1584    }
1585
1586    fn load_magic_properties(class: &'static ClassType, properties: &'static [PropertyInfo]) -> Vec<MagicProperty> {
1587        let configuration = BsonConfiguration::instance();
1588        let mut magic: Vec<MagicProperty> = Vec::with_capacity(properties.len());
1589        for (index, property) in properties.iter().enumerate() {
1590            let name = configuration.alias_for(class.id(), property.name);
1591            let ignored = configuration.is_ignored(class.id(), property.name);
1592            let ignored_if_null = configuration.is_ignored_if_null(class.id(), property.name);
1593            // `Dictionary.Add` of a key that is present.
1594            assert!(
1595                !magic.iter().any(|p| equals_ignore_case(p.name(), &name)),
1596                "An item with the same key has already been added. Key: {}",
1597                name
1598            );
1599            magic.push(MagicProperty::new(property, index, name, ignored, ignored_if_null));
1600        }
1601        magic
1602    }
1603}
1604
1605/// A list the deserializer fills.
1606pub struct ListWrapper {
1607    list: Vec<Value>,
1608}
1609
1610impl BaseWrapper for ListWrapper {
1611    fn collection(&mut self) -> Value {
1612        Value::Enumerable(std::mem::take(&mut self.list))
1613    }
1614
1615    fn add(&mut self, value: Value) -> Result<(), Error> {
1616        self.list.push(value);
1617        Ok(())
1618    }
1619
1620    fn create_container(&self, _ty: &Type, _item_type: &Type) -> Option<Value> {
1621        // An interface gets a `List<T>`, a class with a parameterless
1622        // constructor an instance of itself, anything else nothing (and then
1623        // an `ArrayList`): an empty list of values in every case.
1624        Some(Value::Enumerable(Vec::new()))
1625    }
1626
1627    fn set_container(&mut self, container: Option<Value>) -> Result<(), Error> {
1628        self.list = match container {
1629            None => Vec::new(),
1630            Some(Value::Enumerable(list)) => list,
1631            Some(other) => return Err(invalid_cast(&other, "IList")),
1632        };
1633        Ok(())
1634    }
1635}
1636
1637pub struct ListHelper;
1638
1639impl ListHelper {
1640    pub fn get_list_item_type(enumerable_type: &Type) -> Type {
1641        match enumerable_type {
1642            Type::Array(item) => **item,
1643            Type::List(item) | Type::Collection(item) => **item,
1644            // `GetGenericArguments()[0]` of a dictionary is its key type.
1645            Type::Dictionary(_) => Type::String,
1646            _ => Type::Object,
1647        }
1648    }
1649
1650    pub fn get_dictionary_key_type(enumerable_type: &Type) -> Type {
1651        match enumerable_type {
1652            Type::Dictionary(_) => Type::String,
1653            Type::Array(item) | Type::List(item) | Type::Collection(item) => **item,
1654            _ => Type::Object,
1655        }
1656    }
1657
1658    pub fn get_dictionary_value_type(enumerable_type: &Type) -> Type {
1659        match enumerable_type {
1660            Type::Dictionary(value) => **value,
1661            _ => Type::Object,
1662        }
1663    }
1664
1665    pub fn create_dictionary(_dictionary_type: &Type, _key_type: &Type, _value_type: &Type) -> Dictionary {
1666        Dictionary::new()
1667    }
1668}
1669
1670/// A collection that is not a list, which the deserializer fills.
1671pub struct CollectionWrapper {
1672    list: Vec<Value>,
1673}
1674
1675impl BaseWrapper for CollectionWrapper {
1676    fn collection(&mut self) -> Value {
1677        Value::Enumerable(std::mem::take(&mut self.list))
1678    }
1679
1680    fn add(&mut self, value: Value) -> Result<(), Error> {
1681        self.list.push(value);
1682        Ok(())
1683    }
1684
1685    fn create_container(&self, _ty: &Type, _item_type: &Type) -> Option<Value> {
1686        Some(Value::Enumerable(Vec::new()))
1687    }
1688
1689    fn set_container(&mut self, container: Option<Value>) -> Result<(), Error> {
1690        self.list = match container {
1691            None => Vec::new(),
1692            Some(Value::Enumerable(list)) => list,
1693            Some(other) => return Err(invalid_cast(&other, "ICollection`1")),
1694        };
1695        Ok(())
1696    }
1697}
1698
1699/// What the deserializer adds the items of an array element to. The casts of
1700/// the items to the item type, which the generic wrappers of the original
1701/// make in `Add`, are made when the collection is assigned to its property
1702/// ([`BsonValue::from_value`]).
1703pub trait BaseWrapper {
1704    fn add(&mut self, value: Value) -> Result<(), Error>;
1705    /// The collection that was filled. The wrapper is empty afterwards.
1706    fn collection(&mut self) -> Value;
1707
1708    fn create_container(&self, ty: &Type, item_type: &Type) -> Option<Value>;
1709    fn set_container(&mut self, container: Option<Value>) -> Result<(), Error>;
1710}
1711
1712impl dyn BaseWrapper {
1713    pub fn create(
1714        ty: &Type,
1715        item_type: &Type,
1716        existing_container: Option<Value>,
1717    ) -> Result<Box<dyn BaseWrapper>, Error> {
1718        // The original takes the type of the existing container when there is
1719        // one; a container here is of the declared type of its property.
1720        let mut instance = <dyn BaseWrapper>::create_wrapper_from_type(ty, item_type)?;
1721        let container = match existing_container {
1722            Some(container) => Some(container),
1723            None => instance.create_container(ty, item_type),
1724        };
1725        instance.set_container(container)?;
1726        Ok(instance)
1727    }
1728
1729    fn create_wrapper_from_type(ty: &Type, _item_type: &Type) -> Result<Box<dyn BaseWrapper>, Error> {
1730        match ty {
1731            Type::Array(_) | Type::ByteArray => Ok(Box::new(ArrayWrapper { list: Vec::new() })),
1732            Type::List(_) | Type::Enumerable => Ok(Box::new(ListWrapper { list: Vec::new() })),
1733            Type::Collection(_) | Type::Dictionary(_) => Ok(Box::new(CollectionWrapper { list: Vec::new() })),
1734            // a last-ditch pass: a string is an enumerable of characters.
1735            Type::String => Ok(Box::new(ListWrapper { list: Vec::new() })),
1736            other => Err(BsonException::with_message(format!(
1737                "Collection of type {} cannot be deserialized",
1738                other.full_name()
1739            ))
1740            .into()),
1741        }
1742    }
1743}
1744
1745/// An array the deserializer fills.
1746pub struct ArrayWrapper {
1747    list: Vec<Value>,
1748}
1749
1750impl BaseWrapper for ArrayWrapper {
1751    fn add(&mut self, value: Value) -> Result<(), Error> {
1752        self.list.push(value);
1753        Ok(())
1754    }
1755
1756    fn create_container(&self, _ty: &Type, _item_type: &Type) -> Option<Value> {
1757        None
1758    }
1759
1760    fn set_container(&mut self, container: Option<Value>) -> Result<(), Error> {
1761        if container.is_some() {
1762            return Err(
1763                BsonException::with_message("An container cannot exist when trying to deserialize an array").into()
1764            );
1765        }
1766        Ok(())
1767    }
1768
1769    fn collection(&mut self) -> Value {
1770        Value::Enumerable(std::mem::take(&mut self.list))
1771    }
1772}
1773
1774pub struct Helper;
1775
1776impl Helper {
1777    /// The first of January 1970, 00:00:00 UTC.
1778    pub const EPOCH: DateTime = DateTime::from_unix_ticks(0);
1779}
1780
1781pub struct Document {
1782    pub length: i32,
1783    pub parent: Option<Box<Document>>,
1784    pub digested: i32,
1785}
1786
1787/// `Deserializer.Options`.
1788#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1789pub struct Options {
1790    pub long_integers: bool,
1791    pub string_dates: bool,
1792}
1793
1794/// `System.IO.BinaryReader` over a block of bytes: little-endian numbers,
1795/// an `EndOfStreamException` when a number is cut short.
1796pub struct BinaryReader<'a> {
1797    data: &'a [u8],
1798    position: usize,
1799}
1800
1801impl<'a> BinaryReader<'a> {
1802    pub fn new(data: &'a [u8]) -> BinaryReader<'a> {
1803        BinaryReader { data, position: 0 }
1804    }
1805
1806    fn read_array<const N: usize>(&mut self) -> Result<[u8; N], Error> {
1807        if self.data.len() - self.position < N {
1808            self.position = self.data.len();
1809            return Err(Error::EndOfStream);
1810        }
1811        let mut bytes = [0u8; N];
1812        bytes.copy_from_slice(&self.data[self.position..self.position + N]);
1813        self.position += N;
1814        Ok(bytes)
1815    }
1816
1817    pub fn read_byte(&mut self) -> Result<u8, Error> {
1818        Ok(self.read_array::<1>()?[0])
1819    }
1820
1821    pub fn read_boolean(&mut self) -> Result<bool, Error> {
1822        Ok(self.read_byte()? != 0)
1823    }
1824
1825    pub fn read_int32(&mut self) -> Result<i32, Error> {
1826        Ok(i32::from_le_bytes(self.read_array()?))
1827    }
1828
1829    pub fn read_int64(&mut self) -> Result<i64, Error> {
1830        Ok(i64::from_le_bytes(self.read_array()?))
1831    }
1832
1833    pub fn read_double(&mut self) -> Result<f64, Error> {
1834        Ok(f64::from_le_bytes(self.read_array()?))
1835    }
1836
1837    /// `ReadBytes(count)`: fewer bytes than asked for at the end of the data
1838    /// (not an error); a negative count is an `ArgumentOutOfRangeException`.
1839    pub fn read_bytes(&mut self, count: i32) -> Result<Vec<u8>, Error> {
1840        if count < 0 {
1841            return Err(Error::Argument("Non-negative number required. (Parameter 'count')".to_string()));
1842        }
1843        let end = self.data.len().min(self.position + count as usize);
1844        let bytes = self.data[self.position..end].to_vec();
1845        self.position = end;
1846        Ok(bytes)
1847    }
1848}
1849
1850pub struct Deserializer<'r, 'a> {
1851    reader: &'r mut BinaryReader<'a>,
1852    current: Option<Box<Document>>,
1853}
1854
1855impl<'r, 'a> Deserializer<'r, 'a> {
1856    /// `_typeMap`: the type an element is read as where no declared type
1857    /// says. `None` for an element type that is not in the map; `Some(None)`
1858    /// for null, whose type is null.
1859    fn type_map(stored_type: StoredType) -> Option<Option<Type>> {
1860        Some(Some(match stored_type.known()? {
1861            Types::Int32 => Type::Int32,
1862            Types::Int64 => Type::Int64,
1863            Types::Boolean => Type::Boolean,
1864            Types::String => Type::String,
1865            Types::Double => Type::Double,
1866            Types::Binary => Type::ByteArray,
1867            Types::Regex => Type::Regex,
1868            Types::DateTime => Type::DateTime,
1869            Types::ObjectId => Type::ObjectId,
1870            Types::Array => Type::List(&Type::Object),
1871            Types::Object => Type::Dictionary(&Type::Object),
1872            Types::Null => return Some(None),
1873            _ => return None,
1874        }))
1875    }
1876
1877    fn new(reader: &'r mut BinaryReader<'a>) -> Self {
1878        Deserializer { reader, current: None }
1879    }
1880
1881    /// `Deserialize<T>(byte[] objectData, Options options = null)`.
1882    pub fn deserialize<T: BsonValue>(object_data: &[u8], options: Option<Options>) -> Result<T, Error> {
1883        let mut reader = BinaryReader::new(object_data);
1884        let value = Deserializer::new(&mut reader).read(&T::TYPE, options.unwrap_or_default())?;
1885        T::from_value(value)
1886    }
1887
1888    /// `Deserialize(BinaryReader stream, Type t, Options options = null)`.
1889    pub fn deserialize_type(
1890        stream: &'r mut BinaryReader<'a>,
1891        t: &Type,
1892        options: Option<Options>,
1893    ) -> Result<Value, Error> {
1894        Deserializer::new(stream).read(t, options.unwrap_or_default())
1895    }
1896
1897    /// `Read(Type t, Options options)` and `Read<T>(Options options)`.
1898    fn read(&mut self, t: &Type, options: Options) -> Result<Value, Error> {
1899        let length = self.reader.read_int32()?;
1900        self.new_document(length);
1901        self.deserialize_value(Some(*t), StoredType(Types::Object as i32 as u8), options)
1902    }
1903
1904    /// `Read(int read)`.
1905    fn read_count(&mut self, read: i32) -> Result<(), Error> {
1906        self.current.as_mut().ok_or(Error::NullReference)?.digested += read;
1907        Ok(())
1908    }
1909
1910    fn is_done(&mut self) -> Result<bool, Error> {
1911        let current = self.current.as_ref().ok_or(Error::NullReference)?;
1912        let is_done = current.digested + 1 == current.length;
1913        if is_done {
1914            self.reader.read_byte()?; // EOO
1915            let old = *self.current.take().ok_or(Error::NullReference)?;
1916            self.current = old.parent;
1917            if self.current.is_some() {
1918                self.read_count(old.length)?;
1919            }
1920        }
1921        Ok(is_done)
1922    }
1923
1924    fn new_document(&mut self, length: i32) {
1925        let old = self.current.take();
1926        self.current = Some(Box::new(Document { length, parent: old, digested: 4 }));
1927    }
1928
1929    fn deserialize_value(
1930        &mut self,
1931        ty: Option<Type>,
1932        stored_type: StoredType,
1933        options: Options,
1934    ) -> Result<Value, Error> {
1935        self.deserialize_value_into(ty, stored_type, None, options)
1936    }
1937
1938    /// `DeserializeValue(Type type, Types storedType, object container, Options options)`.
1939    fn deserialize_value_into(
1940        &mut self,
1941        ty: Option<Type>,
1942        stored_type: StoredType,
1943        container: Option<Value>,
1944        options: Options,
1945    ) -> Result<Value, Error> {
1946        if stored_type.is(Types::Null) {
1947            return Ok(Value::Null);
1948        }
1949        let mut ty = ty.ok_or(Error::NullReference)?;
1950        while let Type::Nullable(underlying) = ty {
1951            ty = *underlying;
1952        }
1953        if matches!(ty, Type::String) {
1954            return Ok(Value::String(self.read_string()?));
1955        }
1956        if matches!(ty, Type::Int32) {
1957            let val = self.read_int(stored_type)?;
1958            return Ok(if options.long_integers { Value::Int64(val as i64) } else { Value::Int32(val) });
1959        }
1960        if let Type::Enum(underlying) = ty {
1961            return self.read_enum(underlying, stored_type);
1962        }
1963        if matches!(ty, Type::Single) {
1964            self.read_count(8)?;
1965            return Ok(Value::Single(self.reader.read_double()? as f32));
1966        }
1967        if stored_type.is(Types::Binary) {
1968            return self.read_binary();
1969        }
1970        if ty.is_enumerable() {
1971            return self.read_list(&ty, container, options);
1972        }
1973        if matches!(ty, Type::Boolean) {
1974            self.read_count(1)?;
1975            return Ok(Value::Boolean(self.reader.read_boolean()?));
1976        }
1977        if matches!(ty, Type::DateTime) {
1978            let value = DateTime::from_unix_milliseconds(self.read_long(StoredType(Types::Int64 as i32 as u8))?)?;
1979            return Ok(if options.string_dates {
1980                Value::String(value.to_sortable_string())
1981            } else {
1982                Value::DateTime(value)
1983            });
1984        }
1985        if matches!(ty, Type::ObjectId) {
1986            self.read_count(12)?;
1987            return Ok(Value::ObjectId(ObjectId::from_bytes(self.reader.read_bytes(12)?)));
1988        }
1989        if matches!(ty, Type::Int64) {
1990            return Ok(Value::Int64(self.read_long(stored_type)?));
1991        }
1992        if matches!(ty, Type::Double) {
1993            self.read_count(8)?;
1994            return Ok(Value::Double(self.reader.read_double()?));
1995        }
1996        if matches!(ty, Type::Regex) {
1997            return self.read_regular_expression();
1998        }
1999        if matches!(ty, Type::ScopedCode) {
2000            return Ok(Value::ScopedCode(Box::new(self.read_scoped_code(options)?)));
2001        }
2002        self.read_object(&ty, options)
2003    }
2004
2005    fn read_object(&mut self, ty: &Type, options: Options) -> Result<Value, Error> {
2006        let class = match ty {
2007            Type::Class(class) => *class,
2008            Type::Object => Object::CLASS,
2009            // Deviation (DEVIATIONS.md, Remote protocol): for a type that is
2010            // not a class (a `Guid` whose element is not binary, an item of a
2011            // `byte[]` that was written as an array) the original creates a
2012            // default value of the type and reads the rest of the enclosing
2013            // document as members it does not have. The port reports the
2014            // mismatch.
2015            other => {
2016                return Err(Error::InvalidCast(format!(
2017                    "An element cannot be read as an object of type '{}'.",
2018                    other.full_name()
2019                )))
2020            }
2021        };
2022        let mut instance = (class.create_instance)();
2023        let type_helper = TypeHelper::get_helper_for_type(class);
2024        loop {
2025            let storage_type = self.read_type()?;
2026            let name = self.read_name()?;
2027            let mut is_null = false;
2028            if storage_type.is(Types::Object) {
2029                let length = self.reader.read_int32()?;
2030                if length == 5 {
2031                    self.reader.read_byte()?; //eoo
2032                    self.read_count(5)?;
2033                    is_null = true;
2034                } else {
2035                    self.new_document(length);
2036                }
2037            }
2038            let mut container = None;
2039            let property = type_helper.find_property(&name);
2040            let property_type = match property {
2041                Some(property) => *property.property_type(),
2042                None => Deserializer::type_map(storage_type).flatten().unwrap_or(Type::Object),
2043            };
2044            if let Some(property) = property {
2045                if !property.has_setter() {
2046                    container = Some(property.getter(&*instance).to_value());
2047                }
2048            }
2049            let has_container = container.is_some();
2050            let value = if is_null {
2051                Value::Null
2052            } else {
2053                self.deserialize_value_into(Some(property_type), storage_type, container, options)?
2054            };
2055            match property {
2056                None => {
2057                    if type_helper.expando().is_some() {
2058                        if let Some(expando) = instance.as_expando() {
2059                            expando.expando().set(name, value);
2060                        }
2061                    }
2062                }
2063                Some(property) => {
2064                    if !has_container && !value.is_null() && !property.ignored() {
2065                        property.setter(&mut *instance, value)?;
2066                    } else if has_container && !value.is_null() {
2067                        // The original fills the container of a property
2068                        // without a setter in place. The container here is a
2069                        // copy of the content, so it is stored back.
2070                        property.setter(&mut *instance, value)?;
2071                    }
2072                }
2073            }
2074            if self.is_done()? {
2075                break;
2076            }
2077        }
2078        Ok(Value::Object(instance))
2079    }
2080
2081    fn read_list(
2082        &mut self,
2083        list_type: &Type,
2084        existing_container: Option<Value>,
2085        options: Options,
2086    ) -> Result<Value, Error> {
2087        if Deserializer::is_dictionary(list_type) {
2088            return self.read_dictionary(list_type, existing_container, options);
2089        }
2090
2091        let length = self.reader.read_int32()?;
2092        self.new_document(length);
2093        let item_type = ListHelper::get_list_item_type(list_type);
2094        let is_object = matches!(item_type, Type::Object);
2095        let mut wrapper = <dyn BaseWrapper>::create(list_type, &item_type, existing_container)?;
2096
2097        while !self.is_done()? {
2098            let storage_type = self.read_type()?;
2099            self.read_name()?;
2100            if storage_type.is(Types::Object) {
2101                let length = self.reader.read_int32()?;
2102                self.new_document(length);
2103            }
2104            let specific_item_type =
2105                if is_object { Deserializer::key_of_type_map(storage_type)? } else { Some(item_type) };
2106            let value = self.deserialize_value(specific_item_type, storage_type, options)?;
2107            wrapper.add(value)?;
2108        }
2109        Ok(wrapper.collection())
2110    }
2111
2112    /// `_typeMap[storageType]`: a `KeyNotFoundException` for an element type
2113    /// that is not in the map.
2114    fn key_of_type_map(storage_type: StoredType) -> Result<Option<Type>, Error> {
2115        Deserializer::type_map(storage_type).ok_or_else(|| {
2116            Error::KeyNotFound(format!("The given key '{}' was not present in the dictionary.", storage_type))
2117        })
2118    }
2119
2120    fn is_dictionary(ty: &Type) -> bool {
2121        matches!(ty, Type::Dictionary(_))
2122    }
2123
2124    fn read_dictionary(
2125        &mut self,
2126        list_type: &Type,
2127        existing_container: Option<Value>,
2128        options: Options,
2129    ) -> Result<Value, Error> {
2130        let value_type = ListHelper::get_dictionary_value_type(list_type);
2131        let is_object = matches!(value_type, Type::Object);
2132        let mut container = match existing_container {
2133            None => {
2134                ListHelper::create_dictionary(list_type, &ListHelper::get_dictionary_key_type(list_type), &value_type)
2135            }
2136            Some(Value::Dictionary(dictionary)) => dictionary,
2137            Some(other) => return Err(invalid_cast(&other, "IDictionary")),
2138        };
2139
2140        while !self.is_done()? {
2141            let storage_type = self.read_type()?;
2142
2143            let key = self.read_name()?;
2144            if storage_type.is(Types::Object) {
2145                let length = self.reader.read_int32()?;
2146                self.new_document(length);
2147            }
2148            let specific_item_type =
2149                if is_object { Deserializer::key_of_type_map(storage_type)? } else { Some(value_type) };
2150            let value = self.deserialize_value(specific_item_type, storage_type, options)?;
2151            container.add(key, value)?;
2152        }
2153        Ok(Value::Dictionary(container))
2154    }
2155
2156    fn read_binary(&mut self) -> Result<Value, Error> {
2157        let length = self.reader.read_int32()?;
2158        let sub_type = self.reader.read_byte()?;
2159        self.read_count(5i32.wrapping_add(length))?;
2160        if sub_type == 2 {
2161            let count = self.reader.read_int32()?;
2162            return Ok(Value::ByteArray(self.reader.read_bytes(count)?));
2163        }
2164        if sub_type == 3 {
2165            return Ok(Value::Guid(Guid::from_byte_array(&self.reader.read_bytes(length)?)?));
2166        }
2167        Err(BsonException::with_message(format!("No support for binary type: {}", sub_type)).into())
2168    }
2169
2170    fn read_name(&mut self) -> Result<String, Error> {
2171        let mut buffer = Vec::with_capacity(128); //todo: use a pool to prevent fragmentation
2172        loop {
2173            let b = self.reader.read_byte()?;
2174            if b == 0 {
2175                break;
2176            }
2177            buffer.push(b);
2178        }
2179        self.read_count(buffer.len() as i32 + 1)?;
2180        Ok(String::from_utf8_lossy(&buffer).into_owned())
2181    }
2182
2183    fn read_string(&mut self) -> Result<String, Error> {
2184        let length = self.reader.read_int32()?;
2185        let buffer = self.reader.read_bytes(length.wrapping_sub(1))?; //todo: again, look at fragmentation prevention
2186        self.reader.read_byte()?; //null;
2187        self.read_count(4i32.wrapping_add(length))?;
2188
2189        Ok(String::from_utf8_lossy(&buffer).into_owned())
2190    }
2191
2192    fn read_int(&mut self, stored_type: StoredType) -> Result<i32, Error> {
2193        match stored_type.known() {
2194            Some(Types::Int32) => {
2195                self.read_count(4)?;
2196                self.reader.read_int32()
2197            }
2198            Some(Types::Int64) => {
2199                self.read_count(8)?;
2200                Ok(self.reader.read_int64()? as i32)
2201            }
2202            Some(Types::Double) => {
2203                self.read_count(8)?;
2204                // The unchecked conversion of the original is unspecified for
2205                // a number an `int` cannot hold; the conversion here saturates.
2206                Ok(self.reader.read_double()? as i32)
2207            }
2208            _ => Err(BsonException::with_message(format!("Could not create an int from {}", stored_type)).into()),
2209        }
2210    }
2211
2212    fn read_long(&mut self, stored_type: StoredType) -> Result<i64, Error> {
2213        match stored_type.known() {
2214            Some(Types::Int32) => {
2215                self.read_count(4)?;
2216                Ok(self.reader.read_int32()? as i64)
2217            }
2218            Some(Types::Int64) => {
2219                self.read_count(8)?;
2220                self.reader.read_int64()
2221            }
2222            Some(Types::Double) => {
2223                self.read_count(8)?;
2224                Ok(self.reader.read_double()? as i64)
2225            }
2226            _ => Err(BsonException::with_message(format!("Could not create an int64 from {}", stored_type)).into()),
2227        }
2228    }
2229
2230    /// `ReadEnum(Type type, Types storedType)`: the number of the member,
2231    /// which `Enum.Parse` turns into a value of the enumeration. A number the
2232    /// underlying type cannot hold is an `OverflowException`.
2233    fn read_enum(&mut self, underlying: Types, stored_type: StoredType) -> Result<Value, Error> {
2234        let value = if stored_type.is(Types::Int64) {
2235            self.read_long(stored_type)?
2236        } else {
2237            self.read_int(stored_type)? as i64
2238        };
2239        if underlying == Types::Int32 && i32::try_from(value).is_err() {
2240            return Err(Error::Overflow("Value was either too large or too small for an Int32.".to_string()));
2241        }
2242        Ok(Value::Enum { value, underlying })
2243    }
2244
2245    fn read_regular_expression(&mut self) -> Result<Value, Error> {
2246        let pattern = self.read_name()?;
2247        let options_string = self.read_name()?;
2248
2249        let mut options = RegexOptions::Compiled;
2250        if options_string.contains('e') {
2251            options = options | RegexOptions::ECMAScript;
2252        }
2253        if options_string.contains('i') {
2254            options = options | RegexOptions::IgnoreCase;
2255        }
2256        if options_string.contains('l') {
2257            options = options | RegexOptions::CultureInvariant;
2258        }
2259        if options_string.contains('m') {
2260            options = options | RegexOptions::Multiline;
2261        }
2262        if options_string.contains('s') {
2263            options = options | RegexOptions::Singleline;
2264        }
2265        if options_string.contains('w') {
2266            options = options | RegexOptions::IgnorePatternWhitespace;
2267        }
2268        if options_string.contains('x') {
2269            options = options | RegexOptions::ExplicitCapture;
2270        }
2271
2272        Ok(Value::Regex(Regex::new(pattern, options)))
2273    }
2274
2275    fn read_type(&mut self) -> Result<StoredType, Error> {
2276        self.read_count(1)?;
2277        Ok(StoredType(self.reader.read_byte()?))
2278    }
2279
2280    fn read_scoped_code(&mut self, options: Options) -> Result<ScopedCode, Error> {
2281        self.reader.read_int32()?; //length
2282        self.read_count(4)?;
2283        let name = self.read_string()?;
2284        let length = self.reader.read_int32()?;
2285        self.new_document(length);
2286        let scope = self.deserialize_value(Some(Type::Object), StoredType(Types::Object as i32 as u8), options)?;
2287        Ok(ScopedCode { code_string: Some(name), scope })
2288    }
2289}
2290
2291/// `System.Object` as a class: what the original instantiates for an element
2292/// it reads as `typeof(object)` (the scope of scoped code, a member of an
2293/// element type that is not in the type map). It has no properties, so the
2294/// members of its document are read and dropped.
2295#[derive(Clone, Debug, Default, PartialEq)]
2296pub struct Object;
2297
2298bson_class!(Object as "Object" {});
2299
2300pub mod configuration {
2301    //! `Metsys.Bson.Configuration`: aliases of properties and the properties
2302    //! to leave out, per class.
2303    //!
2304    //! The original names a property with an expression (`x => x.Name`) and
2305    //! reads the name from the expression tree. Here the property is named
2306    //! by its declared name, so the two forms of `Ignore` take the same
2307    //! argument and `ExpressionHelper` has no counterpart.
2308
2309    use std::any::TypeId;
2310    use std::collections::{HashMap, HashSet};
2311    use std::marker::PhantomData;
2312    use std::sync::{Mutex, OnceLock};
2313
2314    pub trait ITypeConfiguration<T: 'static> {
2315        fn use_alias(&self, expression: &str, alias: &str) -> &dyn ITypeConfiguration<T>;
2316        fn ignore(&self, expression: &str) -> &dyn ITypeConfiguration<T>;
2317        /// `Ignore(string name)`.
2318        fn ignore_name(&self, name: &str) -> &dyn ITypeConfiguration<T>;
2319        fn ignore_if_null(&self, expression: &str) -> &dyn ITypeConfiguration<T>;
2320    }
2321
2322    pub struct TypeConfiguration<T: 'static> {
2323        configuration: &'static BsonConfiguration,
2324        marker: PhantomData<fn() -> T>,
2325    }
2326
2327    impl<T: 'static> TypeConfiguration<T> {
2328        pub(crate) fn new(configuration: &'static BsonConfiguration) -> Self {
2329            TypeConfiguration { configuration, marker: PhantomData }
2330        }
2331    }
2332
2333    impl<T: 'static> ITypeConfiguration<T> for TypeConfiguration<T> {
2334        fn use_alias(&self, expression: &str, alias: &str) -> &dyn ITypeConfiguration<T> {
2335            self.configuration.add_map::<T>(expression, alias);
2336            self
2337        }
2338
2339        fn ignore(&self, expression: &str) -> &dyn ITypeConfiguration<T> {
2340            self.ignore_name(expression)
2341        }
2342
2343        fn ignore_name(&self, name: &str) -> &dyn ITypeConfiguration<T> {
2344            self.configuration.add_ignore::<T>(name);
2345            self
2346        }
2347
2348        fn ignore_if_null(&self, expression: &str) -> &dyn ITypeConfiguration<T> {
2349            self.configuration.add_ignore_if_null::<T>(expression);
2350            self
2351        }
2352    }
2353
2354    /// The configuration of the serializer. A class is configured before its
2355    /// first object is written or read: the properties of a class are loaded
2356    /// once.
2357    pub struct BsonConfiguration {
2358        alias_map: Mutex<HashMap<TypeId, HashMap<String, String>>>,
2359        ignored: Mutex<HashMap<TypeId, HashSet<String>>>,
2360        ignored_if_null: Mutex<HashMap<TypeId, HashSet<String>>>,
2361    }
2362
2363    impl BsonConfiguration {
2364        // The original says of its instance "not thread safe"; a static of
2365        // Rust has to be, so the tables are behind locks.
2366        pub fn instance() -> &'static BsonConfiguration {
2367            static INSTANCE: OnceLock<BsonConfiguration> = OnceLock::new();
2368            INSTANCE.get_or_init(BsonConfiguration::new)
2369        }
2370
2371        fn new() -> BsonConfiguration {
2372            BsonConfiguration {
2373                alias_map: Mutex::new(HashMap::new()),
2374                ignored: Mutex::new(HashMap::new()),
2375                ignored_if_null: Mutex::new(HashMap::new()),
2376            }
2377        }
2378
2379        pub fn for_type<T: 'static>(action: impl FnOnce(&dyn ITypeConfiguration<T>)) {
2380            action(&TypeConfiguration::<T>::new(BsonConfiguration::instance()));
2381        }
2382
2383        pub fn add_map<T: 'static>(&self, property: &str, alias: &str) {
2384            let mut alias_map = self.alias_map.lock().unwrap();
2385            alias_map.entry(TypeId::of::<T>()).or_default().insert(property.to_string(), alias.to_string());
2386        }
2387
2388        pub fn alias_for(&self, ty: TypeId, property: &str) -> String {
2389            let alias_map = self.alias_map.lock().unwrap();
2390            match alias_map.get(&ty).and_then(|map| map.get(property)) {
2391                Some(value) => value.clone(),
2392                None => property.to_string(),
2393            }
2394        }
2395
2396        pub fn add_ignore<T: 'static>(&self, name: &str) {
2397            let mut ignored = self.ignored.lock().unwrap();
2398            ignored.entry(TypeId::of::<T>()).or_default().insert(name.to_string());
2399        }
2400
2401        pub fn is_ignored(&self, ty: TypeId, name: &str) -> bool {
2402            let ignored = self.ignored.lock().unwrap();
2403            ignored.get(&ty).is_some_and(|list| list.contains(name))
2404        }
2405
2406        pub fn add_ignore_if_null<T: 'static>(&self, name: &str) {
2407            let mut ignored_if_null = self.ignored_if_null.lock().unwrap();
2408            ignored_if_null.entry(TypeId::of::<T>()).or_default().insert(name.to_string());
2409        }
2410
2411        pub fn is_ignored_if_null(&self, ty: TypeId, name: &str) -> bool {
2412            let ignored_if_null = self.ignored_if_null.lock().unwrap();
2413            ignored_if_null.get(&ty).is_some_and(|list| list.contains(name))
2414        }
2415    }
2416}
2417
2418#[derive(Clone, Debug, Default)]
2419pub struct BsonException {
2420    message: Option<String>,
2421    inner_exception: Option<Arc<dyn std::error::Error + Send + Sync>>,
2422}
2423
2424impl BsonException {
2425    pub fn new() -> BsonException {
2426        BsonException::default()
2427    }
2428
2429    pub fn with_message(message: impl Into<String>) -> BsonException {
2430        BsonException { message: Some(message.into()), inner_exception: None }
2431    }
2432
2433    pub fn with_inner_exception(
2434        message: impl Into<String>,
2435        inner_exception: Arc<dyn std::error::Error + Send + Sync>,
2436    ) -> BsonException {
2437        BsonException { message: Some(message.into()), inner_exception: Some(inner_exception) }
2438    }
2439
2440    /// `Exception.Message`.
2441    pub fn message(&self) -> &str {
2442        self.message.as_deref().unwrap_or("Exception of type 'Metsys.Bson.BsonException' was thrown.")
2443    }
2444}
2445
2446impl fmt::Display for BsonException {
2447    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2448        f.write_str(self.message())
2449    }
2450}
2451
2452impl std::error::Error for BsonException {
2453    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
2454        match &self.inner_exception {
2455            Some(inner) => Some(&**inner),
2456            None => None,
2457        }
2458    }
2459}