From fbba5fbd001b28a3269015374c91ca28afd96c17 Mon Sep 17 00:00:00 2001 From: Abraham Egnor Date: Tue, 27 Sep 2022 14:31:28 -0400 Subject: [PATCH] RUST-1480 Add a TryFrom impl for RawBson --- src/raw/bson.rs | 39 +++++++++++++++++++++++++++++++++++++++ src/raw/document_buf.rs | 8 ++++++++ 2 files changed, 47 insertions(+) diff --git a/src/raw/bson.rs b/src/raw/bson.rs index 638ca57c..9db28505 100644 --- a/src/raw/bson.rs +++ b/src/raw/bson.rs @@ -482,6 +482,45 @@ impl TryFrom for Bson { } } +impl TryFrom for RawBson { + type Error = Error; + + fn try_from(bson: Bson) -> Result { + Ok(match bson { + Bson::Double(d) => RawBson::Double(d), + Bson::String(s) => RawBson::String(s), + Bson::Document(doc) => RawBson::Document((&doc).try_into()?), + Bson::Array(arr) => RawBson::Array( + arr.into_iter() + .map(|b| -> Result { b.try_into() }) + .collect::>()?, + ), + Bson::Binary(bin) => RawBson::Binary(bin), + Bson::ObjectId(id) => RawBson::ObjectId(id), + Bson::Boolean(b) => RawBson::Boolean(b), + Bson::DateTime(dt) => RawBson::DateTime(dt), + Bson::Null => RawBson::Null, + Bson::RegularExpression(regex) => RawBson::RegularExpression(regex), + Bson::JavaScriptCode(s) => RawBson::JavaScriptCode(s), + Bson::Int32(i) => RawBson::Int32(i), + Bson::Timestamp(ts) => RawBson::Timestamp(ts), + Bson::Int64(i) => RawBson::Int64(i), + Bson::Undefined => RawBson::Undefined, + Bson::DbPointer(p) => RawBson::DbPointer(p), + Bson::Symbol(s) => RawBson::Symbol(s), + Bson::JavaScriptCodeWithScope(jcws) => { + RawBson::JavaScriptCodeWithScope(crate::RawJavaScriptCodeWithScope { + code: jcws.code, + scope: (&jcws.scope).try_into()?, + }) + } + Bson::Decimal128(d) => RawBson::Decimal128(d), + Bson::MaxKey => RawBson::MaxKey, + Bson::MinKey => RawBson::MinKey, + }) + } +} + /// A BSON "code with scope" value backed by owned raw BSON. #[derive(Debug, Clone, PartialEq)] pub struct RawJavaScriptCodeWithScope { diff --git a/src/raw/document_buf.rs b/src/raw/document_buf.rs index 5624506e..0a27396a 100644 --- a/src/raw/document_buf.rs +++ b/src/raw/document_buf.rs @@ -361,6 +361,14 @@ impl TryFrom for Document { } } +impl TryFrom<&Document> for RawDocumentBuf { + type Error = Error; + + fn try_from(doc: &Document) -> Result { + RawDocumentBuf::from_document(doc) + } +} + impl<'a> IntoIterator for &'a RawDocumentBuf { type IntoIter = Iter<'a>; type Item = Result<(&'a str, RawBsonRef<'a>)>;