Coverage Report

Created: 2026-12-01 06:31

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/bson-rust/src/raw/bson.rs
Line
Count
Source
1
use std::convert::{TryFrom, TryInto};
2
3
#[cfg(feature = "facet-unstable")]
4
use crate::facet::opaque;
5
use crate::{
6
    Binary,
7
    Bson,
8
    DbPointer,
9
    Decimal128,
10
    RawArray,
11
    RawArrayBuf,
12
    RawBinaryRef,
13
    RawBsonRef,
14
    RawDbPointerRef,
15
    RawDocument,
16
    RawDocumentBuf,
17
    RawJavaScriptCodeWithScopeRef,
18
    RawRegexRef,
19
    Regex,
20
    Timestamp,
21
    oid::{self, ObjectId},
22
    raw::check_recursion_limit,
23
    spec::ElementType,
24
};
25
26
use super::{Error, Result};
27
28
/// A BSON value backed by owned raw BSON bytes.
29
///
30
/// Note that `RawBson`'s [`PartialEq`] implementation is byte value equality, so
31
/// `RawBson::Double(v)` and `v` may compare differently.
32
#[derive(Debug, Clone)]
33
#[cfg_attr(
34
    feature = "facet-unstable",
35
    repr(C),
36
    derive(facet::Facet),
37
    facet(opaque = crate::facet::opaque::RawBsonAdapter)
38
)]
39
pub enum RawBson {
40
    /// 64-bit binary floating point
41
    Double(f64),
42
    /// UTF-8 string
43
    String(String),
44
    /// Array
45
    Array(RawArrayBuf),
46
    /// Embedded document
47
    Document(RawDocumentBuf),
48
    /// Boolean value
49
    Boolean(bool),
50
    /// Null value
51
    Null,
52
    /// Regular expression
53
    RegularExpression(Regex),
54
    /// JavaScript code
55
    JavaScriptCode(String),
56
    /// JavaScript code w/ scope
57
    JavaScriptCodeWithScope(RawJavaScriptCodeWithScope),
58
    /// 32-bit signed integer
59
    Int32(i32),
60
    /// 64-bit signed integer
61
    Int64(i64),
62
    /// Timestamp
63
    Timestamp(Timestamp),
64
    /// Binary data
65
    Binary(Binary),
66
    /// [ObjectId](http://dochub.mongodb.org/core/objectids)
67
    ObjectId(oid::ObjectId),
68
    /// UTC datetime
69
    DateTime(crate::DateTime),
70
    /// Symbol (Deprecated)
71
    Symbol(String),
72
    /// [128-bit decimal floating point](https://github.com/mongodb/specifications/blob/master/source/bson-decimal128/decimal128.rst)
73
    Decimal128(Decimal128),
74
    /// Undefined value (Deprecated)
75
    Undefined,
76
    /// Max key
77
    MaxKey,
78
    /// Min key
79
    MinKey,
80
    /// DBPointer (Deprecated)
81
    DbPointer(DbPointer),
82
}
83
84
impl RawBson {
85
    /// Get the [`ElementType`] of this value.
86
0
    pub fn element_type(&self) -> ElementType {
87
0
        match *self {
88
0
            RawBson::Double(..) => ElementType::Double,
89
0
            RawBson::String(..) => ElementType::String,
90
0
            RawBson::Array(..) => ElementType::Array,
91
0
            RawBson::Document(..) => ElementType::EmbeddedDocument,
92
0
            RawBson::Boolean(..) => ElementType::Boolean,
93
0
            RawBson::Null => ElementType::Null,
94
0
            RawBson::RegularExpression(..) => ElementType::RegularExpression,
95
0
            RawBson::JavaScriptCode(..) => ElementType::JavaScriptCode,
96
0
            RawBson::JavaScriptCodeWithScope(..) => ElementType::JavaScriptCodeWithScope,
97
0
            RawBson::Int32(..) => ElementType::Int32,
98
0
            RawBson::Int64(..) => ElementType::Int64,
99
0
            RawBson::Timestamp(..) => ElementType::Timestamp,
100
0
            RawBson::Binary(..) => ElementType::Binary,
101
0
            RawBson::ObjectId(..) => ElementType::ObjectId,
102
0
            RawBson::DateTime(..) => ElementType::DateTime,
103
0
            RawBson::Symbol(..) => ElementType::Symbol,
104
0
            RawBson::Decimal128(..) => ElementType::Decimal128,
105
0
            RawBson::Undefined => ElementType::Undefined,
106
0
            RawBson::MaxKey => ElementType::MaxKey,
107
0
            RawBson::MinKey => ElementType::MinKey,
108
0
            RawBson::DbPointer(..) => ElementType::DbPointer,
109
        }
110
0
    }
111
112
    /// Gets the wrapped `f64` value or returns [`None`] if the value isn't a BSON
113
    /// double.
114
0
    pub fn as_f64(&self) -> Option<f64> {
115
0
        match self {
116
0
            RawBson::Double(d) => Some(*d),
117
0
            _ => None,
118
        }
119
0
    }
120
121
    /// Gets a reference to the [`String`] that's wrapped or returns [`None`] if the wrapped value
122
    /// isn't a BSON String.
123
0
    pub fn as_str(&self) -> Option<&'_ str> {
124
0
        match self {
125
0
            RawBson::String(s) => Some(s),
126
0
            _ => None,
127
        }
128
0
    }
129
130
    /// Gets a reference to the [`RawArrayBuf`] that's wrapped or returns [`None`] if the wrapped
131
    /// value isn't a BSON array.
132
0
    pub fn as_array(&self) -> Option<&'_ RawArray> {
133
0
        match self {
134
0
            RawBson::Array(v) => Some(v),
135
0
            _ => None,
136
        }
137
0
    }
138
139
    /// Gets a mutable reference to the [`RawArrayBuf`] that's wrapped or returns [`None`] if the
140
    /// wrapped value isn't a BSON array.
141
0
    pub fn as_array_mut(&mut self) -> Option<&mut RawArrayBuf> {
142
0
        match self {
143
0
            RawBson::Array(v) => Some(v),
144
0
            _ => None,
145
        }
146
0
    }
147
148
    /// Gets a reference to the [`RawDocumentBuf`] that's wrapped or returns [`None`] if the wrapped
149
    /// value isn't a BSON document.
150
0
    pub fn as_document(&self) -> Option<&'_ RawDocument> {
151
0
        match self {
152
0
            RawBson::Document(v) => Some(v),
153
0
            _ => None,
154
        }
155
0
    }
156
157
    /// Gets a mutable reference to the [`RawDocumentBuf`] that's wrapped or returns [`None`] if the
158
    /// wrapped value isn't a BSON document.
159
0
    pub fn as_document_mut(&mut self) -> Option<&mut RawDocumentBuf> {
160
0
        match self {
161
0
            RawBson::Document(v) => Some(v),
162
0
            _ => None,
163
        }
164
0
    }
165
166
    /// Gets the wrapped `bool` value or returns [`None`] if the wrapped value isn't a BSON
167
    /// boolean.
168
0
    pub fn as_bool(&self) -> Option<bool> {
169
0
        match self {
170
0
            RawBson::Boolean(v) => Some(*v),
171
0
            _ => None,
172
        }
173
0
    }
174
175
    /// Gets the wrapped `i32` value or returns [`None`] if the wrapped value isn't a BSON
176
    /// Int32.
177
0
    pub fn as_i32(&self) -> Option<i32> {
178
0
        match self {
179
0
            RawBson::Int32(v) => Some(*v),
180
0
            _ => None,
181
        }
182
0
    }
183
184
    /// Gets the wrapped `i64` value or returns [`None`] if the wrapped value isn't a BSON
185
    /// Int64.
186
0
    pub fn as_i64(&self) -> Option<i64> {
187
0
        match self {
188
0
            RawBson::Int64(v) => Some(*v),
189
0
            _ => None,
190
        }
191
0
    }
192
193
    /// Gets the wrapped [`crate::oid::ObjectId`] value or returns [`None`] if the wrapped value
194
    /// isn't a BSON ObjectID.
195
0
    pub fn as_object_id(&self) -> Option<oid::ObjectId> {
196
0
        match self {
197
0
            RawBson::ObjectId(v) => Some(*v),
198
0
            _ => None,
199
        }
200
0
    }
201
202
    /// Gets a reference to the [`Binary`] that's wrapped or returns [`None`] if the wrapped value
203
    /// isn't a BSON binary.
204
0
    pub fn as_binary(&self) -> Option<RawBinaryRef<'_>> {
205
0
        match self {
206
0
            RawBson::Binary(v) => Some(RawBinaryRef {
207
0
                bytes: v.bytes.as_slice(),
208
0
                subtype: v.subtype,
209
0
            }),
210
0
            _ => None,
211
        }
212
0
    }
213
214
    /// Gets a reference to the [`Regex`] that's wrapped or returns [`None`] if the wrapped value
215
    /// isn't a BSON regular expression.
216
0
    pub fn as_regex(&self) -> Option<RawRegexRef<'_>> {
217
0
        match self {
218
0
            RawBson::RegularExpression(v) => Some(RawRegexRef {
219
0
                pattern: v.pattern.as_ref(),
220
0
                options: v.options.as_ref(),
221
0
            }),
222
0
            _ => None,
223
        }
224
0
    }
225
226
    /// Gets the wrapped [`crate::DateTime`] value or returns [`None`] if the wrapped value isn't a
227
    /// BSON datetime.
228
0
    pub fn as_datetime(&self) -> Option<crate::DateTime> {
229
0
        match self {
230
0
            RawBson::DateTime(v) => Some(*v),
231
0
            _ => None,
232
        }
233
0
    }
234
235
    /// Gets a reference to the symbol that's wrapped or returns [`None`] if the wrapped value isn't
236
    /// a BSON Symbol.
237
0
    pub fn as_symbol(&self) -> Option<&'_ str> {
238
0
        match self {
239
0
            RawBson::Symbol(v) => Some(v),
240
0
            _ => None,
241
        }
242
0
    }
243
244
    /// Gets the wrapped [`crate::Timestamp`] value or returns [`None`] if the wrapped value isn't a
245
    /// BSON datetime.
246
0
    pub fn as_timestamp(&self) -> Option<Timestamp> {
247
0
        match self {
248
0
            RawBson::Timestamp(timestamp) => Some(*timestamp),
249
0
            _ => None,
250
        }
251
0
    }
252
253
    /// Returns `Some(())` if this value is null, otherwise returns [`None`].
254
0
    pub fn as_null(&self) -> Option<()> {
255
0
        match self {
256
0
            RawBson::Null => Some(()),
257
0
            _ => None,
258
        }
259
0
    }
260
261
    /// Gets a reference to the [`crate::DbPointer`] that's wrapped or returns [`None`] if the
262
    /// wrapped value isn't a BSON DbPointer.
263
0
    pub fn as_db_pointer(&self) -> Option<RawDbPointerRef<'_>> {
264
0
        match self {
265
0
            RawBson::DbPointer(d) => Some(RawDbPointerRef {
266
0
                namespace: d.namespace.as_str(),
267
0
                id: d.id,
268
0
            }),
269
0
            _ => None,
270
        }
271
0
    }
272
273
    /// Gets a reference to the code that's wrapped or returns [`None`] if the wrapped value isn't a
274
    /// BSON JavaScript code.
275
0
    pub fn as_javascript(&self) -> Option<&'_ str> {
276
0
        match self {
277
0
            RawBson::JavaScriptCode(s) => Some(s),
278
0
            _ => None,
279
        }
280
0
    }
281
282
    /// Gets a reference to the [`RawJavaScriptCodeWithScope`] that's wrapped or returns [`None`]
283
    /// if the wrapped value isn't a BSON JavaScript code with scope value.
284
0
    pub fn as_javascript_with_scope(&self) -> Option<RawJavaScriptCodeWithScopeRef<'_>> {
285
0
        match self {
286
0
            RawBson::JavaScriptCodeWithScope(s) => Some(RawJavaScriptCodeWithScopeRef {
287
0
                code: s.code.as_str(),
288
0
                scope: &s.scope,
289
0
            }),
290
0
            _ => None,
291
        }
292
0
    }
293
294
    /// Gets a [`RawBsonRef`] value referencing this owned raw BSON value.
295
0
    pub fn as_raw_bson_ref(&self) -> RawBsonRef<'_> {
296
0
        match self {
297
0
            RawBson::Double(d) => RawBsonRef::Double(*d),
298
0
            RawBson::String(s) => RawBsonRef::String(s.as_str()),
299
0
            RawBson::Array(a) => RawBsonRef::Array(a),
300
0
            RawBson::Document(d) => RawBsonRef::Document(d),
301
0
            RawBson::Boolean(b) => RawBsonRef::Boolean(*b),
302
0
            RawBson::Null => RawBsonRef::Null,
303
0
            RawBson::RegularExpression(re) => RawBsonRef::RegularExpression(RawRegexRef {
304
0
                options: re.options.as_ref(),
305
0
                pattern: re.pattern.as_ref(),
306
0
            }),
307
0
            RawBson::JavaScriptCode(c) => RawBsonRef::JavaScriptCode(c.as_str()),
308
0
            RawBson::JavaScriptCodeWithScope(code_w_scope) => {
309
0
                RawBsonRef::JavaScriptCodeWithScope(RawJavaScriptCodeWithScopeRef {
310
0
                    code: code_w_scope.code.as_str(),
311
0
                    scope: code_w_scope.scope.as_ref(),
312
0
                })
313
            }
314
0
            RawBson::Int32(i) => RawBsonRef::Int32(*i),
315
0
            RawBson::Int64(i) => RawBsonRef::Int64(*i),
316
0
            RawBson::Timestamp(ts) => RawBsonRef::Timestamp(*ts),
317
0
            RawBson::Binary(b) => RawBsonRef::Binary(RawBinaryRef {
318
0
                bytes: b.bytes.as_slice(),
319
0
                subtype: b.subtype,
320
0
            }),
321
0
            RawBson::ObjectId(oid) => RawBsonRef::ObjectId(*oid),
322
0
            RawBson::DateTime(dt) => RawBsonRef::DateTime(*dt),
323
0
            RawBson::Symbol(s) => RawBsonRef::Symbol(s.as_str()),
324
0
            RawBson::Decimal128(d) => RawBsonRef::Decimal128(*d),
325
0
            RawBson::Undefined => RawBsonRef::Undefined,
326
0
            RawBson::MaxKey => RawBsonRef::MaxKey,
327
0
            RawBson::MinKey => RawBsonRef::MinKey,
328
0
            RawBson::DbPointer(dbp) => RawBsonRef::DbPointer(RawDbPointerRef {
329
0
                namespace: dbp.namespace.as_str(),
330
0
                id: dbp.id,
331
0
            }),
332
        }
333
0
    }
334
335
0
    pub(crate) fn try_into_parsed(self, depth: u32) -> Result<Bson> {
336
0
        check_recursion_limit(depth)?;
337
0
        Ok(match self {
338
0
            Self::Double(d) => Bson::Double(d),
339
0
            Self::String(s) => Bson::String(s),
340
0
            Self::Document(rawdoc) => Bson::Document(rawdoc.try_into_parsed(depth)?),
341
0
            Self::Array(rawarray) => Bson::Array(rawarray.try_into_parsed(depth)?),
342
0
            Self::Binary(rawbson) => Bson::Binary(rawbson),
343
0
            Self::ObjectId(rawbson) => Bson::ObjectId(rawbson),
344
0
            Self::Boolean(rawbson) => Bson::Boolean(rawbson),
345
0
            Self::DateTime(rawbson) => Bson::DateTime(rawbson),
346
0
            Self::Null => Bson::Null,
347
0
            Self::RegularExpression(rawregex) => Bson::RegularExpression(rawregex),
348
0
            Self::JavaScriptCode(rawbson) => Bson::JavaScriptCode(rawbson),
349
0
            Self::Int32(rawbson) => Bson::Int32(rawbson),
350
0
            Self::Timestamp(rawbson) => Bson::Timestamp(rawbson),
351
0
            Self::Int64(rawbson) => Bson::Int64(rawbson),
352
0
            Self::Undefined => Bson::Undefined,
353
0
            Self::DbPointer(rawbson) => Bson::DbPointer(rawbson),
354
0
            Self::Symbol(rawbson) => Bson::Symbol(rawbson),
355
0
            Self::JavaScriptCodeWithScope(rawbson) => {
356
                Bson::JavaScriptCodeWithScope(crate::JavaScriptCodeWithScope {
357
0
                    code: rawbson.code,
358
0
                    scope: rawbson.scope.try_into_parsed(depth.saturating_add(1))?,
359
                })
360
            }
361
0
            Self::Decimal128(rawbson) => Bson::Decimal128(rawbson),
362
0
            Self::MaxKey => Bson::MaxKey,
363
0
            Self::MinKey => Bson::MinKey,
364
        })
365
0
    }
366
}
367
368
impl PartialEq for RawBson {
369
0
    fn eq(&self, other: &Self) -> bool {
370
0
        match self {
371
0
            Self::Double(s) => matches!(other, Self::Double(o) if s.to_bits() == o.to_bits()),
372
0
            Self::String(s) => matches!(other, Self::String(o) if s == o),
373
0
            Self::Array(s) => matches!(other, Self::Array(o) if s == o),
374
0
            Self::Document(s) => matches!(other, Self::Document(o) if s == o),
375
0
            Self::Boolean(s) => matches!(other, Self::Boolean(o) if s == o),
376
0
            Self::RegularExpression(s) => {
377
0
                matches!(other, Self::RegularExpression(o) if s == o)
378
            }
379
0
            Self::JavaScriptCode(s) => matches!(other, Self::JavaScriptCode(o) if s == o),
380
0
            Self::JavaScriptCodeWithScope(s) => {
381
0
                matches!(other, Self::JavaScriptCodeWithScope(o) if s == o)
382
            }
383
0
            Self::Int32(s) => matches!(other, Self::Int32(o) if s == o),
384
0
            Self::Int64(s) => matches!(other, Self::Int64(o) if s == o),
385
0
            Self::Timestamp(s) => matches!(other, Self::Timestamp(o) if s == o),
386
0
            Self::Binary(s) => matches!(other, Self::Binary(o) if s == o),
387
0
            Self::ObjectId(s) => matches!(other, Self::ObjectId(o) if s == o),
388
0
            Self::DateTime(s) => matches!(other, Self::DateTime(o) if s == o),
389
0
            Self::Symbol(s) => matches!(other, Self::Symbol(o) if s == o),
390
0
            Self::Decimal128(s) => matches!(other, Self::Decimal128(o) if s == o),
391
0
            Self::DbPointer(s) => matches!(other, Self::DbPointer(o) if s == o),
392
0
            Self::Null => matches!(other, Self::Null),
393
0
            Self::Undefined => matches!(other, Self::Undefined),
394
0
            Self::MaxKey => matches!(other, Self::MaxKey),
395
0
            Self::MinKey => matches!(other, Self::MinKey),
396
        }
397
0
    }
398
}
399
400
impl Eq for RawBson {}
401
402
impl std::hash::Hash for RawBson {
403
0
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
404
0
        std::mem::discriminant(self).hash(state);
405
0
        match self {
406
0
            Self::Double(double) => double.to_bits().hash(state),
407
0
            Self::String(x) => x.hash(state),
408
0
            Self::Array(x) => x.hash(state),
409
0
            Self::Document(x) => x.hash(state),
410
0
            Self::Boolean(x) => x.hash(state),
411
0
            Self::RegularExpression(x) => x.hash(state),
412
0
            Self::JavaScriptCode(x) => x.hash(state),
413
0
            Self::JavaScriptCodeWithScope(x) => x.hash(state),
414
0
            Self::Int32(x) => x.hash(state),
415
0
            Self::Int64(x) => x.hash(state),
416
0
            Self::Timestamp(x) => x.hash(state),
417
0
            Self::Binary(x) => x.hash(state),
418
0
            Self::ObjectId(x) => x.hash(state),
419
0
            Self::DateTime(x) => x.hash(state),
420
0
            Self::Symbol(x) => x.hash(state),
421
0
            Self::Decimal128(x) => x.hash(state),
422
0
            Self::DbPointer(x) => x.hash(state),
423
0
            Self::Null | Self::Undefined | Self::MaxKey | Self::MinKey => (),
424
        }
425
0
    }
426
}
427
428
impl From<i32> for RawBson {
429
0
    fn from(i: i32) -> Self {
430
0
        RawBson::Int32(i)
431
0
    }
432
}
433
434
impl From<i64> for RawBson {
435
0
    fn from(i: i64) -> Self {
436
0
        RawBson::Int64(i)
437
0
    }
438
}
439
440
impl From<u32> for RawBson {
441
0
    fn from(n: u32) -> Self {
442
0
        if let Ok(n) = i32::try_from(n) {
443
0
            RawBson::Int32(n)
444
        } else {
445
0
            RawBson::Int64(n.into())
446
        }
447
0
    }
448
}
449
450
impl From<String> for RawBson {
451
0
    fn from(s: String) -> Self {
452
0
        RawBson::String(s)
453
0
    }
454
}
455
456
impl From<&str> for RawBson {
457
0
    fn from(s: &str) -> Self {
458
0
        RawBson::String(s.to_owned())
459
0
    }
460
}
461
462
impl From<f64> for RawBson {
463
0
    fn from(f: f64) -> Self {
464
0
        RawBson::Double(f)
465
0
    }
466
}
467
468
impl From<bool> for RawBson {
469
0
    fn from(b: bool) -> Self {
470
0
        RawBson::Boolean(b)
471
0
    }
472
}
473
474
impl From<RawDocumentBuf> for RawBson {
475
0
    fn from(d: RawDocumentBuf) -> Self {
476
0
        RawBson::Document(d)
477
0
    }
478
}
479
480
impl From<RawArrayBuf> for RawBson {
481
0
    fn from(a: RawArrayBuf) -> Self {
482
0
        RawBson::Array(a)
483
0
    }
484
}
485
486
impl From<crate::DateTime> for RawBson {
487
0
    fn from(dt: crate::DateTime) -> Self {
488
0
        RawBson::DateTime(dt)
489
0
    }
490
}
491
492
impl From<Timestamp> for RawBson {
493
0
    fn from(ts: Timestamp) -> Self {
494
0
        RawBson::Timestamp(ts)
495
0
    }
496
}
497
498
impl From<ObjectId> for RawBson {
499
0
    fn from(oid: ObjectId) -> Self {
500
0
        RawBson::ObjectId(oid)
501
0
    }
502
}
503
504
impl From<Decimal128> for RawBson {
505
0
    fn from(d: Decimal128) -> Self {
506
0
        RawBson::Decimal128(d)
507
0
    }
508
}
509
510
impl From<RawJavaScriptCodeWithScope> for RawBson {
511
0
    fn from(code_w_scope: RawJavaScriptCodeWithScope) -> Self {
512
0
        RawBson::JavaScriptCodeWithScope(code_w_scope)
513
0
    }
514
}
515
516
impl From<Binary> for RawBson {
517
0
    fn from(b: Binary) -> Self {
518
0
        RawBson::Binary(b)
519
0
    }
520
}
521
522
impl From<Regex> for RawBson {
523
0
    fn from(re: Regex) -> Self {
524
0
        RawBson::RegularExpression(re)
525
0
    }
526
}
527
528
impl From<DbPointer> for RawBson {
529
0
    fn from(d: DbPointer) -> Self {
530
0
        RawBson::DbPointer(d)
531
0
    }
532
}
533
534
#[cfg(feature = "serde")]
535
impl<'de> serde::Deserialize<'de> for RawBson {
536
0
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
537
0
    where
538
0
        D: serde::Deserializer<'de>,
539
    {
540
        use super::serde::{OwnedOrBorrowedRawBson, bson_visitor::OwnedOrBorrowedRawBsonVisitor};
541
0
        match deserializer.deserialize_newtype_struct(
542
            crate::raw::RAW_BSON_NEWTYPE,
543
0
            OwnedOrBorrowedRawBsonVisitor,
544
0
        )? {
545
0
            OwnedOrBorrowedRawBson::Owned(o) => Ok(o),
546
0
            OwnedOrBorrowedRawBson::Borrowed(b) => Ok(b.into()),
547
        }
548
0
    }
549
}
550
551
#[cfg(feature = "serde")]
552
impl serde::Serialize for RawBson {
553
0
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
554
0
    where
555
0
        S: serde::Serializer,
556
    {
557
0
        self.as_raw_bson_ref().serialize(serializer)
558
0
    }
559
}
560
561
impl TryFrom<RawBson> for Bson {
562
    type Error = Error;
563
564
0
    fn try_from(rawbson: RawBson) -> Result<Bson> {
565
0
        rawbson.try_into_parsed(0)
566
0
    }
567
}
568
569
impl TryFrom<Bson> for RawBson {
570
    type Error = crate::error::Error;
571
572
0
    fn try_from(bson: Bson) -> crate::error::Result<RawBson> {
573
0
        Ok(match bson {
574
0
            Bson::Double(d) => RawBson::Double(d),
575
0
            Bson::String(s) => RawBson::String(s),
576
0
            Bson::Document(doc) => RawBson::Document(doc.try_into()?),
577
0
            Bson::Array(arr) => RawBson::Array(arr.try_into()?),
578
0
            Bson::Binary(bin) => RawBson::Binary(bin),
579
0
            Bson::ObjectId(id) => RawBson::ObjectId(id),
580
0
            Bson::Boolean(b) => RawBson::Boolean(b),
581
0
            Bson::DateTime(dt) => RawBson::DateTime(dt),
582
0
            Bson::Null => RawBson::Null,
583
0
            Bson::RegularExpression(regex) => RawBson::RegularExpression(regex),
584
0
            Bson::JavaScriptCode(s) => RawBson::JavaScriptCode(s),
585
0
            Bson::Int32(i) => RawBson::Int32(i),
586
0
            Bson::Timestamp(ts) => RawBson::Timestamp(ts),
587
0
            Bson::Int64(i) => RawBson::Int64(i),
588
0
            Bson::Undefined => RawBson::Undefined,
589
0
            Bson::DbPointer(p) => RawBson::DbPointer(p),
590
0
            Bson::Symbol(s) => RawBson::Symbol(s),
591
0
            Bson::JavaScriptCodeWithScope(jcws) => {
592
                RawBson::JavaScriptCodeWithScope(crate::RawJavaScriptCodeWithScope {
593
0
                    code: jcws.code,
594
0
                    scope: jcws.scope.try_into()?,
595
                })
596
            }
597
0
            Bson::Decimal128(d) => RawBson::Decimal128(d),
598
0
            Bson::MaxKey => RawBson::MaxKey,
599
0
            Bson::MinKey => RawBson::MinKey,
600
        })
601
0
    }
602
}
603
604
/// A BSON "code with scope" value backed by owned raw BSON.
605
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
606
#[cfg_attr(feature = "facet-unstable", derive(facet::Facet), facet(opaque = opaque::RawJavaScriptCodeWithScopeAdapter))]
607
pub struct RawJavaScriptCodeWithScope {
608
    /// The code value.
609
    pub code: String,
610
611
    /// The scope document.
612
    pub scope: RawDocumentBuf,
613
}
614
615
impl TryFrom<RawJavaScriptCodeWithScope> for crate::JavaScriptCodeWithScope {
616
    type Error = crate::raw::Error;
617
618
0
    fn try_from(value: RawJavaScriptCodeWithScope) -> crate::raw::Result<Self> {
619
        Ok(Self {
620
0
            code: value.code,
621
0
            scope: value.scope.try_into()?,
622
        })
623
0
    }
624
}
625
626
impl TryFrom<crate::JavaScriptCodeWithScope> for RawJavaScriptCodeWithScope {
627
    type Error = crate::raw::Error;
628
629
0
    fn try_from(value: crate::JavaScriptCodeWithScope) -> std::result::Result<Self, Self::Error> {
630
        Ok(Self {
631
0
            code: value.code,
632
0
            scope: value.scope.try_into()?,
633
        })
634
0
    }
635
}
636
637
impl TryFrom<RawJavaScriptCodeWithScope> for Bson {
638
    type Error = crate::raw::Error;
639
640
0
    fn try_from(value: RawJavaScriptCodeWithScope) -> crate::raw::Result<Self> {
641
0
        value.try_into().map(Bson::JavaScriptCodeWithScope)
642
0
    }
643
}
644
645
#[cfg(feature = "serde")]
646
impl<'de> serde::Deserialize<'de> for RawJavaScriptCodeWithScope {
647
0
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
648
0
    where
649
0
        D: serde::Deserializer<'de>,
650
    {
651
0
        match RawBson::deserialize(deserializer)? {
652
0
            RawBson::JavaScriptCodeWithScope(b) => Ok(b),
653
0
            c => Err(serde::de::Error::custom(format!(
654
0
                "expected CodeWithScope, but got {:?} instead",
655
0
                c
656
0
            ))),
657
        }
658
0
    }
659
}
660
661
#[cfg(feature = "serde")]
662
impl serde::Serialize for RawJavaScriptCodeWithScope {
663
0
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
664
0
    where
665
0
        S: serde::Serializer,
666
    {
667
0
        let raw = RawJavaScriptCodeWithScopeRef {
668
0
            code: self.code.as_str(),
669
0
            scope: self.scope.as_ref(),
670
0
        };
671
672
0
        raw.serialize(serializer)
673
0
    }
674
}
675
676
impl<'a> From<&'a RawJavaScriptCodeWithScope> for RawJavaScriptCodeWithScopeRef<'a> {
677
0
    fn from(value: &'a RawJavaScriptCodeWithScope) -> Self {
678
0
        RawJavaScriptCodeWithScopeRef {
679
0
            code: &value.code,
680
0
            scope: &value.scope,
681
0
        }
682
0
    }
683
}