Skip to content

Commit a4c0526

Browse files
authored
RUST-1480 Add a TryFrom<Bson> impl for RawBson (#373)
1 parent bad1468 commit a4c0526

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

src/raw/bson.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -482,6 +482,45 @@ impl TryFrom<RawBson> for Bson {
482482
}
483483
}
484484

485+
impl TryFrom<Bson> for RawBson {
486+
type Error = Error;
487+
488+
fn try_from(bson: Bson) -> Result<RawBson> {
489+
Ok(match bson {
490+
Bson::Double(d) => RawBson::Double(d),
491+
Bson::String(s) => RawBson::String(s),
492+
Bson::Document(doc) => RawBson::Document((&doc).try_into()?),
493+
Bson::Array(arr) => RawBson::Array(
494+
arr.into_iter()
495+
.map(|b| -> Result<RawBson> { b.try_into() })
496+
.collect::<Result<RawArrayBuf>>()?,
497+
),
498+
Bson::Binary(bin) => RawBson::Binary(bin),
499+
Bson::ObjectId(id) => RawBson::ObjectId(id),
500+
Bson::Boolean(b) => RawBson::Boolean(b),
501+
Bson::DateTime(dt) => RawBson::DateTime(dt),
502+
Bson::Null => RawBson::Null,
503+
Bson::RegularExpression(regex) => RawBson::RegularExpression(regex),
504+
Bson::JavaScriptCode(s) => RawBson::JavaScriptCode(s),
505+
Bson::Int32(i) => RawBson::Int32(i),
506+
Bson::Timestamp(ts) => RawBson::Timestamp(ts),
507+
Bson::Int64(i) => RawBson::Int64(i),
508+
Bson::Undefined => RawBson::Undefined,
509+
Bson::DbPointer(p) => RawBson::DbPointer(p),
510+
Bson::Symbol(s) => RawBson::Symbol(s),
511+
Bson::JavaScriptCodeWithScope(jcws) => {
512+
RawBson::JavaScriptCodeWithScope(crate::RawJavaScriptCodeWithScope {
513+
code: jcws.code,
514+
scope: (&jcws.scope).try_into()?,
515+
})
516+
}
517+
Bson::Decimal128(d) => RawBson::Decimal128(d),
518+
Bson::MaxKey => RawBson::MaxKey,
519+
Bson::MinKey => RawBson::MinKey,
520+
})
521+
}
522+
}
523+
485524
/// A BSON "code with scope" value backed by owned raw BSON.
486525
#[derive(Debug, Clone, PartialEq)]
487526
pub struct RawJavaScriptCodeWithScope {

src/raw/document_buf.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -361,6 +361,14 @@ impl TryFrom<RawDocumentBuf> for Document {
361361
}
362362
}
363363

364+
impl TryFrom<&Document> for RawDocumentBuf {
365+
type Error = Error;
366+
367+
fn try_from(doc: &Document) -> Result<RawDocumentBuf> {
368+
RawDocumentBuf::from_document(doc)
369+
}
370+
}
371+
364372
impl<'a> IntoIterator for &'a RawDocumentBuf {
365373
type IntoIter = Iter<'a>;
366374
type Item = Result<(&'a str, RawBsonRef<'a>)>;

0 commit comments

Comments
 (0)