1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
use std::convert::{TryFrom, TryInto};

use serde::{de::Visitor, ser::SerializeStruct, Deserialize, Serialize};
use serde_bytes::{ByteBuf, Bytes};

use super::{Error, RawArray, RawDocument, Result};
use crate::{
    de::convert_unsigned_to_signed_raw,
    extjson,
    oid::{self, ObjectId},
    raw::{RAW_ARRAY_NEWTYPE, RAW_BSON_NEWTYPE, RAW_DOCUMENT_NEWTYPE},
    spec::{BinarySubtype, ElementType},
    Bson,
    DateTime,
    DbPointer,
    Decimal128,
    Timestamp,
};

/// A BSON value referencing raw bytes stored elsewhere.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum RawBson<'a> {
    /// 64-bit binary floating point
    Double(f64),
    /// UTF-8 string
    String(&'a str),
    /// Array
    Array(&'a RawArray),
    /// Embedded document
    Document(&'a RawDocument),
    /// Boolean value
    Boolean(bool),
    /// Null value
    Null,
    /// Regular expression
    RegularExpression(RawRegex<'a>),
    /// JavaScript code
    JavaScriptCode(&'a str),
    /// JavaScript code w/ scope
    JavaScriptCodeWithScope(RawJavaScriptCodeWithScope<'a>),
    /// 32-bit signed integer
    Int32(i32),
    /// 64-bit signed integer
    Int64(i64),
    /// 32-bit signed integer
    UInt32(u32),
    /// 64-bit signed integer
    UInt64(u64),
    /// Timestamp
    Timestamp(Timestamp),
    /// Binary data
    Binary(RawBinary<'a>),
    /// [ObjectId](http://dochub.mongodb.org/core/objectids)
    ObjectId(oid::ObjectId),
    /// UTC datetime
    DateTime(crate::DateTime),
    /// Symbol (Deprecated)
    Symbol(&'a str),
    /// [128-bit decimal floating point](https://github.com/mongodb/specifications/blob/master/source/bson-decimal128/decimal128.rst)
    Decimal128(Decimal128),
    /// Undefined value (Deprecated)
    Undefined,
    /// Max key
    MaxKey,
    /// Min key
    MinKey,
    /// DBPointer (Deprecated)
    DbPointer(RawDbPointer<'a>),
}

impl<'a> RawBson<'a> {
    /// Get the [`ElementType`] of this value.
    pub fn element_type(&self) -> ElementType {
        match *self {
            RawBson::Double(..) => ElementType::Double,
            RawBson::String(..) => ElementType::String,
            RawBson::Array(..) => ElementType::Array,
            RawBson::Document(..) => ElementType::EmbeddedDocument,
            RawBson::Boolean(..) => ElementType::Boolean,
            RawBson::Null => ElementType::Null,
            RawBson::RegularExpression(..) => ElementType::RegularExpression,
            RawBson::JavaScriptCode(..) => ElementType::JavaScriptCode,
            RawBson::JavaScriptCodeWithScope(..) => ElementType::JavaScriptCodeWithScope,
            RawBson::Int32(..) => ElementType::Int32,
            RawBson::Int64(..) => ElementType::Int64,
            RawBson::UInt32(..) => ElementType::UInt32,
            RawBson::UInt64(..) => ElementType::UInt64,
            RawBson::Timestamp(..) => ElementType::Timestamp,
            RawBson::Binary(..) => ElementType::Binary,
            RawBson::ObjectId(..) => ElementType::ObjectId,
            RawBson::DateTime(..) => ElementType::DateTime,
            RawBson::Symbol(..) => ElementType::Symbol,
            RawBson::Decimal128(..) => ElementType::Decimal128,
            RawBson::Undefined => ElementType::Undefined,
            RawBson::MaxKey => ElementType::MaxKey,
            RawBson::MinKey => ElementType::MinKey,
            RawBson::DbPointer(..) => ElementType::DbPointer,
        }
    }

    /// Gets the `f64` that's referenced or returns `None` if the referenced value isn't a BSON
    /// double.
    pub fn as_f64(self) -> Option<f64> {
        match self {
            RawBson::Double(d) => Some(d),
            _ => None,
        }
    }

    /// Gets the `&str` that's referenced or returns `None` if the referenced value isn't a BSON
    /// String.
    pub fn as_str(self) -> Option<&'a str> {
        match self {
            RawBson::String(s) => Some(s),
            _ => None,
        }
    }

    /// Gets the [`RawArray`] that's referenced or returns `None` if the referenced value
    /// isn't a BSON array.
    pub fn as_array(self) -> Option<&'a RawArray> {
        match self {
            RawBson::Array(v) => Some(v),
            _ => None,
        }
    }

    /// Gets the [`RawDocument`] that's referenced or returns `None` if the referenced value
    /// isn't a BSON document.
    pub fn as_document(self) -> Option<&'a RawDocument> {
        match self {
            RawBson::Document(v) => Some(v),
            _ => None,
        }
    }

    /// Gets the `bool` that's referenced or returns `None` if the referenced value isn't a BSON
    /// boolean.
    pub fn as_bool(self) -> Option<bool> {
        match self {
            RawBson::Boolean(v) => Some(v),
            _ => None,
        }
    }

    /// Gets the `i32` that's referenced or returns `None` if the referenced value isn't a BSON
    /// Int32.
    pub fn as_i32(self) -> Option<i32> {
        match self {
            RawBson::Int32(v) => Some(v),
            _ => None,
        }
    }

    /// Gets the `i64` that's referenced or returns `None` if the referenced value isn't a BSON
    /// Int64.
    pub fn as_i64(self) -> Option<i64> {
        match self {
            RawBson::Int64(v) => Some(v),
            _ => None,
        }
    }

    /// Gets the [`crate::oid::ObjectId`] that's referenced or returns `None` if the referenced
    /// value isn't a BSON ObjectID.
    pub fn as_object_id(self) -> Option<oid::ObjectId> {
        match self {
            RawBson::ObjectId(v) => Some(v),
            _ => None,
        }
    }

    /// Gets the [`RawBinary`] that's referenced or returns `None` if the referenced value isn't a
    /// BSON binary.
    pub fn as_binary(self) -> Option<RawBinary<'a>> {
        match self {
            RawBson::Binary(v) => Some(v),
            _ => None,
        }
    }

    /// Gets the [`RawRegex`] that's referenced or returns `None` if the referenced value isn't a
    /// BSON regular expression.
    pub fn as_regex(self) -> Option<RawRegex<'a>> {
        match self {
            RawBson::RegularExpression(v) => Some(v),
            _ => None,
        }
    }

    /// Gets the [`crate::DateTime`] that's referenced or returns `None` if the referenced value
    /// isn't a BSON datetime.
    pub fn as_datetime(self) -> Option<crate::DateTime> {
        match self {
            RawBson::DateTime(v) => Some(v),
            _ => None,
        }
    }

    /// Gets the symbol that's referenced or returns `None` if the referenced value isn't a BSON
    /// symbol.
    pub fn as_symbol(self) -> Option<&'a str> {
        match self {
            RawBson::Symbol(v) => Some(v),
            _ => None,
        }
    }

    /// Gets the [`crate::Timestamp`] that's referenced or returns `None` if the referenced value
    /// isn't a BSON timestamp.
    pub fn as_timestamp(self) -> Option<Timestamp> {
        match self {
            RawBson::Timestamp(timestamp) => Some(timestamp),
            _ => None,
        }
    }

    /// Gets the null value that's referenced or returns `None` if the referenced value isn't a BSON
    /// null.
    pub fn as_null(self) -> Option<()> {
        match self {
            RawBson::Null => Some(()),
            _ => None,
        }
    }

    /// Gets the [`RawDbPointer`] that's referenced or returns `None` if the referenced value isn't
    /// a BSON DB pointer.
    pub fn as_db_pointer(self) -> Option<RawDbPointer<'a>> {
        match self {
            RawBson::DbPointer(d) => Some(d),
            _ => None,
        }
    }

    /// Gets the code that's referenced or returns `None` if the referenced value isn't a BSON
    /// JavaScript.
    pub fn as_javascript(self) -> Option<&'a str> {
        match self {
            RawBson::JavaScriptCode(s) => Some(s),
            _ => None,
        }
    }

    /// Gets the [`RawJavaScriptCodeWithScope`] that's referenced or returns `None` if the
    /// referenced value isn't a BSON JavaScript with scope.
    pub fn as_javascript_with_scope(self) -> Option<RawJavaScriptCodeWithScope<'a>> {
        match self {
            RawBson::JavaScriptCodeWithScope(s) => Some(s),
            _ => None,
        }
    }
}

/// A visitor used to deserialize types backed by raw BSON.
pub(crate) struct RawBsonVisitor;

impl<'de> Visitor<'de> for RawBsonVisitor {
    type Value = RawBson<'de>;

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(formatter, "a raw BSON reference")
    }

    fn visit_borrowed_str<E>(self, v: &'de str) -> std::result::Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(RawBson::String(v))
    }

    fn visit_borrowed_bytes<E>(self, bytes: &'de [u8]) -> std::result::Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(RawBson::Binary(RawBinary {
            bytes,
            subtype: BinarySubtype::Generic,
        }))
    }

    fn visit_i8<E>(self, v: i8) -> std::result::Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(RawBson::Int32(v.into()))
    }

    fn visit_i16<E>(self, v: i16) -> std::result::Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(RawBson::Int32(v.into()))
    }

    fn visit_i32<E>(self, v: i32) -> std::result::Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(RawBson::Int32(v))
    }

    fn visit_i64<E>(self, v: i64) -> std::result::Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(RawBson::Int64(v))
    }

    fn visit_u8<E>(self, value: u8) -> std::result::Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        convert_unsigned_to_signed_raw(value.into())
    }

    fn visit_u16<E>(self, value: u16) -> std::result::Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        convert_unsigned_to_signed_raw(value.into())
    }

    fn visit_u32<E>(self, value: u32) -> std::result::Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        convert_unsigned_to_signed_raw(value.into())
    }

    fn visit_u64<E>(self, value: u64) -> std::result::Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        convert_unsigned_to_signed_raw(value)
    }

    fn visit_bool<E>(self, v: bool) -> std::result::Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(RawBson::Boolean(v))
    }

    fn visit_f64<E>(self, v: f64) -> std::result::Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(RawBson::Double(v))
    }

    fn visit_none<E>(self) -> std::result::Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(RawBson::Null)
    }

    fn visit_unit<E>(self) -> std::result::Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(RawBson::Null)
    }

    fn visit_newtype_struct<D>(self, deserializer: D) -> std::result::Result<Self::Value, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        deserializer.deserialize_any(self)
    }

    fn visit_map<A>(self, mut map: A) -> std::result::Result<Self::Value, A::Error>
    where
        A: serde::de::MapAccess<'de>,
    {
        let k = map
            .next_key::<&str>()?
            .ok_or_else(|| serde::de::Error::custom("expected a key when deserializing RawBson"))?;
        match k {
            "$oid" => {
                let oid: ObjectId = map.next_value()?;
                Ok(RawBson::ObjectId(oid))
            }
            "$symbol" => {
                let s: &str = map.next_value()?;
                Ok(RawBson::Symbol(s))
            }
            "$numberDecimalBytes" => {
                let bytes = map.next_value::<ByteBuf>()?;
                return Ok(RawBson::Decimal128(Decimal128::deserialize_from_slice(
                    &bytes,
                )?));
            }
            "$regularExpression" => {
                #[derive(Debug, Deserialize)]
                struct BorrowedRegexBody<'a> {
                    pattern: &'a str,

                    options: &'a str,
                }
                let body: BorrowedRegexBody = map.next_value()?;
                Ok(RawBson::RegularExpression(RawRegex {
                    pattern: body.pattern,
                    options: body.options,
                }))
            }
            "$undefined" => {
                let _: bool = map.next_value()?;
                Ok(RawBson::Undefined)
            }
            "$binary" => {
                #[derive(Debug, Deserialize)]
                struct BorrowedBinaryBody<'a> {
                    bytes: &'a [u8],

                    #[serde(rename = "subType")]
                    subtype: u8,
                }

                let v = map.next_value::<BorrowedBinaryBody>()?;

                Ok(RawBson::Binary(RawBinary {
                    bytes: v.bytes,
                    subtype: v.subtype.into(),
                }))
            }
            "$date" => {
                let v = map.next_value::<i64>()?;
                Ok(RawBson::DateTime(DateTime::from_millis(v)))
            }
            "$timestamp" => {
                let v = map.next_value::<extjson::models::TimestampBody>()?;
                Ok(RawBson::Timestamp(Timestamp {
                    time: v.t,
                    increment: v.i,
                }))
            }
            "$minKey" => {
                let _ = map.next_value::<i32>()?;
                Ok(RawBson::MinKey)
            }
            "$maxKey" => {
                let _ = map.next_value::<i32>()?;
                Ok(RawBson::MaxKey)
            }
            "$code" => {
                let code = map.next_value::<&str>()?;
                if let Some(key) = map.next_key::<&str>()? {
                    if key == "$scope" {
                        let scope = map.next_value::<&RawDocument>()?;
                        Ok(RawBson::JavaScriptCodeWithScope(
                            RawJavaScriptCodeWithScope { code, scope },
                        ))
                    } else {
                        Err(serde::de::Error::unknown_field(key, &["$scope"]))
                    }
                } else {
                    Ok(RawBson::JavaScriptCode(code))
                }
            }
            "$dbPointer" => {
                #[derive(Deserialize)]
                struct BorrowedDbPointerBody<'a> {
                    #[serde(rename = "$ref")]
                    ns: &'a str,

                    #[serde(rename = "$id")]
                    id: ObjectId,
                }

                let body: BorrowedDbPointerBody = map.next_value()?;
                Ok(RawBson::DbPointer(RawDbPointer {
                    namespace: body.ns,
                    id: body.id,
                }))
            }
            RAW_DOCUMENT_NEWTYPE => {
                let bson = map.next_value::<&[u8]>()?;
                let doc = RawDocument::new(bson).map_err(serde::de::Error::custom)?;
                Ok(RawBson::Document(doc))
            }
            RAW_ARRAY_NEWTYPE => {
                let bson = map.next_value::<&[u8]>()?;
                let doc = RawDocument::new(bson).map_err(serde::de::Error::custom)?;
                Ok(RawBson::Array(RawArray::from_doc(doc)))
            }
            k => Err(serde::de::Error::custom(format!(
                "can't deserialize RawBson from map, key={}",
                k
            ))),
        }
    }
}

impl<'de: 'a, 'a> Deserialize<'de> for RawBson<'a> {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        deserializer.deserialize_newtype_struct(RAW_BSON_NEWTYPE, RawBsonVisitor)
    }
}

impl<'a> Serialize for RawBson<'a> {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            RawBson::Double(v) => serializer.serialize_f64(*v),
            RawBson::String(v) => serializer.serialize_str(v),
            RawBson::Array(v) => v.serialize(serializer),
            RawBson::Document(v) => v.serialize(serializer),
            RawBson::Boolean(v) => serializer.serialize_bool(*v),
            RawBson::Null => serializer.serialize_unit(),
            RawBson::Int32(v) => serializer.serialize_i32(*v),
            RawBson::Int64(v) => serializer.serialize_i64(*v),
            RawBson::UInt32(v) => serializer.serialize_u32(*v),
            RawBson::UInt64(v) => serializer.serialize_u64(*v),
            RawBson::ObjectId(oid) => oid.serialize(serializer),
            RawBson::DateTime(dt) => dt.serialize(serializer),
            RawBson::Binary(b) => b.serialize(serializer),
            RawBson::JavaScriptCode(c) => {
                let mut state = serializer.serialize_struct("$code", 1)?;
                state.serialize_field("$code", c)?;
                state.end()
            }
            RawBson::JavaScriptCodeWithScope(code_w_scope) => code_w_scope.serialize(serializer),
            RawBson::DbPointer(dbp) => dbp.serialize(serializer),
            RawBson::Symbol(s) => {
                let mut state = serializer.serialize_struct("$symbol", 1)?;
                state.serialize_field("$symbol", s)?;
                state.end()
            }
            RawBson::RegularExpression(re) => re.serialize(serializer),
            RawBson::Timestamp(t) => t.serialize(serializer),
            RawBson::Decimal128(d) => d.serialize(serializer),
            RawBson::Undefined => {
                let mut state = serializer.serialize_struct("$undefined", 1)?;
                state.serialize_field("$undefined", &true)?;
                state.end()
            }
            RawBson::MaxKey => {
                let mut state = serializer.serialize_struct("$maxKey", 1)?;
                state.serialize_field("$maxKey", &1)?;
                state.end()
            }
            RawBson::MinKey => {
                let mut state = serializer.serialize_struct("$minKey", 1)?;
                state.serialize_field("$minKey", &1)?;
                state.end()
            }
        }
    }
}

impl<'a> TryFrom<RawBson<'a>> for Bson {
    type Error = Error;

    fn try_from(rawbson: RawBson<'a>) -> Result<Bson> {
        Ok(match rawbson {
            RawBson::Double(d) => Bson::Double(d),
            RawBson::String(s) => Bson::String(s.to_string()),
            RawBson::Document(rawdoc) => {
                let doc = rawdoc.try_into()?;
                Bson::Document(doc)
            }
            RawBson::Array(rawarray) => {
                let mut items = Vec::new();
                for v in rawarray {
                    let bson: Bson = v?.try_into()?;
                    items.push(bson);
                }
                Bson::Array(items)
            }
            RawBson::Binary(rawbson) => {
                let RawBinary {
                    subtype,
                    bytes: data,
                } = rawbson;
                Bson::Binary(crate::Binary {
                    subtype,
                    bytes: data.to_vec(),
                })
            }
            RawBson::ObjectId(rawbson) => Bson::ObjectId(rawbson),
            RawBson::Boolean(rawbson) => Bson::Boolean(rawbson),
            RawBson::DateTime(rawbson) => Bson::DateTime(rawbson),
            RawBson::Null => Bson::Null,
            RawBson::RegularExpression(rawregex) => Bson::RegularExpression(crate::Regex::new(
                rawregex.pattern.to_string(),
                rawregex.options.to_string(),
            )),
            RawBson::JavaScriptCode(rawbson) => Bson::JavaScriptCode(rawbson.to_string()),
            RawBson::Int32(rawbson) => Bson::Int32(rawbson),
            RawBson::Timestamp(rawbson) => Bson::Timestamp(rawbson),
            RawBson::Int64(rawbson) => Bson::Int64(rawbson),

            RawBson::UInt32(rawbson) => Bson::UInt32(rawbson),
            RawBson::UInt64(rawbson) => Bson::UInt64(rawbson),
            RawBson::Undefined => Bson::Undefined,
            RawBson::DbPointer(rawbson) => Bson::DbPointer(DbPointer {
                namespace: rawbson.namespace.to_string(),
                id: rawbson.id,
            }),
            RawBson::Symbol(rawbson) => Bson::Symbol(rawbson.to_string()),
            RawBson::JavaScriptCodeWithScope(rawbson) => {
                Bson::JavaScriptCodeWithScope(crate::JavaScriptCodeWithScope {
                    code: rawbson.code.to_string(),
                    scope: rawbson.scope.try_into()?,
                })
            }
            RawBson::Decimal128(rawbson) => Bson::Decimal128(rawbson),
            RawBson::MaxKey => Bson::MaxKey,
            RawBson::MinKey => Bson::MinKey,
        })
    }
}

/// A BSON binary value referencing raw bytes stored elsewhere.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RawBinary<'a> {
    /// The subtype of the binary value.
    pub subtype: BinarySubtype,

    /// The binary bytes.
    pub bytes: &'a [u8],
}

impl<'de: 'a, 'a> Deserialize<'de> for RawBinary<'a> {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        match RawBson::deserialize(deserializer)? {
            RawBson::Binary(b) => Ok(b),
            c => Err(serde::de::Error::custom(format!(
                "expected binary, but got {:?} instead",
                c
            ))),
        }
    }
}

impl<'a> Serialize for RawBinary<'a> {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        if let BinarySubtype::Generic = self.subtype {
            serializer.serialize_bytes(self.bytes)
        } else if !serializer.is_human_readable() {
            #[derive(Serialize)]
            struct BorrowedBinary<'a> {
                bytes: &'a Bytes,

                #[serde(rename = "subType")]
                subtype: u8,
            }

            let mut state = serializer.serialize_struct("$binary", 1)?;
            let body = BorrowedBinary {
                bytes: Bytes::new(self.bytes),
                subtype: self.subtype.into(),
            };
            state.serialize_field("$binary", &body)?;
            state.end()
        } else {
            let mut state = serializer.serialize_struct("$binary", 1)?;
            let body = extjson::models::BinaryBody {
                base64: base64::encode(self.bytes),
                subtype: hex::encode([self.subtype.into()]),
            };
            state.serialize_field("$binary", &body)?;
            state.end()
        }
    }
}

/// A BSON regex referencing raw bytes stored elsewhere.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RawRegex<'a> {
    pub(crate) pattern: &'a str,
    pub(crate) options: &'a str,
}

impl<'a> RawRegex<'a> {
    /// Gets the pattern portion of the regex.
    pub fn pattern(self) -> &'a str {
        self.pattern
    }

    /// Gets the options portion of the regex.
    pub fn options(self) -> &'a str {
        self.options
    }
}

impl<'de: 'a, 'a> Deserialize<'de> for RawRegex<'a> {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        match RawBson::deserialize(deserializer)? {
            RawBson::RegularExpression(b) => Ok(b),
            c => Err(serde::de::Error::custom(format!(
                "expected Regex, but got {:?} instead",
                c
            ))),
        }
    }
}

impl<'a> Serialize for RawRegex<'a> {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        #[derive(Serialize)]
        struct BorrowedRegexBody<'a> {
            pattern: &'a str,
            options: &'a str,
        }

        let mut state = serializer.serialize_struct("$regularExpression", 1)?;
        let body = BorrowedRegexBody {
            pattern: self.pattern,
            options: self.options,
        };
        state.serialize_field("$regularExpression", &body)?;
        state.end()
    }
}

/// A BSON "code with scope" value referencing raw bytes stored elsewhere.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RawJavaScriptCodeWithScope<'a> {
    pub(crate) code: &'a str,

    pub(crate) scope: &'a RawDocument,
}

impl<'a> RawJavaScriptCodeWithScope<'a> {
    /// Gets the code in the value.
    pub fn code(self) -> &'a str {
        self.code
    }

    /// Gets the scope in the value.
    pub fn scope(self) -> &'a RawDocument {
        self.scope
    }
}

impl<'de: 'a, 'a> Deserialize<'de> for RawJavaScriptCodeWithScope<'a> {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        match RawBson::deserialize(deserializer)? {
            RawBson::JavaScriptCodeWithScope(b) => Ok(b),
            c => Err(serde::de::Error::custom(format!(
                "expected CodeWithScope, but got {:?} instead",
                c
            ))),
        }
    }
}

impl<'a> Serialize for RawJavaScriptCodeWithScope<'a> {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let mut state = serializer.serialize_struct("$codeWithScope", 2)?;
        state.serialize_field("$code", &self.code)?;
        state.serialize_field("$scope", &self.scope)?;
        state.end()
    }
}

/// A BSON DB pointer value referencing raw bytes stored elesewhere.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RawDbPointer<'a> {
    pub(crate) namespace: &'a str,
    pub(crate) id: ObjectId,
}

impl<'de: 'a, 'a> Deserialize<'de> for RawDbPointer<'a> {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        match RawBson::deserialize(deserializer)? {
            RawBson::DbPointer(b) => Ok(b),
            c => Err(serde::de::Error::custom(format!(
                "expected DbPointer, but got {:?} instead",
                c
            ))),
        }
    }
}

impl<'a> Serialize for RawDbPointer<'a> {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        #[derive(Serialize)]
        struct BorrowedDbPointerBody<'a> {
            #[serde(rename = "$ref")]
            ref_ns: &'a str,

            #[serde(rename = "$id")]
            id: ObjectId,
        }

        let mut state = serializer.serialize_struct("$dbPointer", 1)?;
        let body = BorrowedDbPointerBody {
            ref_ns: self.namespace,
            id: self.id,
        };
        state.serialize_field("$dbPointer", &body)?;
        state.end()
    }
}