@@ -9,7 +9,11 @@ use crate::{
99 de:: MIN_BSON_DOCUMENT_SIZE ,
1010 error:: { Error , Result } ,
1111 raw:: { error:: ErrorKind , serde:: OwnedOrBorrowedRawDocument , RAW_DOCUMENT_NEWTYPE } ,
12+ Bson ,
1213 DateTime ,
14+ JavaScriptCodeWithScope ,
15+ RawBson ,
16+ RawJavaScriptCodeWithScope ,
1317 Timestamp ,
1418} ;
1519
@@ -532,11 +536,45 @@ impl RawDocument {
532536 /// Copy this into a [`Document`], returning an error if invalid BSON is encountered. Any
533537 /// invalid UTF-8 sequences will be replaced with the Unicode replacement character.
534538 pub fn to_document_utf8_lossy ( & self ) -> Result < Document > {
535- self . iter_elements ( )
536- . map ( |res| {
537- res. and_then ( |e| Ok ( ( e. key ( ) . to_owned ( ) , e. value_utf8_lossy ( ) ?. try_into ( ) ?) ) )
538- } )
539- . collect ( )
539+ let mut out = Document :: new ( ) ;
540+ for elem in self . iter_elements ( ) {
541+ let elem = elem?;
542+ let value = deep_utf8_lossy ( elem. value_utf8_lossy ( ) ?) ?;
543+ out. insert ( elem. key ( ) , value) ;
544+ }
545+ Ok ( out)
546+ }
547+ }
548+
549+ fn deep_utf8_lossy ( src : RawBson ) -> Result < Bson > {
550+ match src {
551+ RawBson :: Array ( arr) => {
552+ let mut tmp = vec ! [ ] ;
553+ for elem in arr. iter_elements ( ) {
554+ tmp. push ( deep_utf8_lossy ( elem?. value_utf8_lossy ( ) ?) ?) ;
555+ }
556+ Ok ( Bson :: Array ( tmp) )
557+ }
558+ RawBson :: Document ( doc) => {
559+ let mut tmp = doc ! { } ;
560+ for elem in doc. iter_elements ( ) {
561+ let elem = elem?;
562+ tmp. insert ( elem. key ( ) , deep_utf8_lossy ( elem. value_utf8_lossy ( ) ?) ?) ;
563+ }
564+ Ok ( Bson :: Document ( tmp) )
565+ }
566+ RawBson :: JavaScriptCodeWithScope ( RawJavaScriptCodeWithScope { code, scope } ) => {
567+ let mut tmp = doc ! { } ;
568+ for elem in scope. iter_elements ( ) {
569+ let elem = elem?;
570+ tmp. insert ( elem. key ( ) , deep_utf8_lossy ( elem. value_utf8_lossy ( ) ?) ?) ;
571+ }
572+ Ok ( Bson :: JavaScriptCodeWithScope ( JavaScriptCodeWithScope {
573+ code,
574+ scope : tmp,
575+ } ) )
576+ }
577+ v => v. try_into ( ) ,
540578 }
541579}
542580
0 commit comments