@@ -8,7 +8,11 @@ use serde::{ser::SerializeMap, Deserialize, Serialize};
88use crate :: {
99 de:: MIN_BSON_DOCUMENT_SIZE ,
1010 raw:: { error:: ErrorKind , serde:: OwnedOrBorrowedRawDocument , RAW_DOCUMENT_NEWTYPE } ,
11+ Bson ,
1112 DateTime ,
13+ JavaScriptCodeWithScope ,
14+ RawBson ,
15+ RawJavaScriptCodeWithScope ,
1216 Timestamp ,
1317} ;
1418
@@ -540,11 +544,45 @@ impl RawDocument {
540544 /// Copy this into a [`Document`], returning an error if invalid BSON is encountered. Any
541545 /// invalid UTF-8 sequences will be replaced with the Unicode replacement character.
542546 pub fn to_document_utf8_lossy ( & self ) -> Result < Document > {
543- self . iter_elements ( )
544- . map ( |res| {
545- res. and_then ( |e| Ok ( ( e. key ( ) . to_owned ( ) , e. value_utf8_lossy ( ) ?. try_into ( ) ?) ) )
546- } )
547- . collect ( )
547+ let mut out = Document :: new ( ) ;
548+ for elem in self . iter_elements ( ) {
549+ let elem = elem?;
550+ let value = deep_utf8_lossy ( elem. value_utf8_lossy ( ) ?) ?;
551+ out. insert ( elem. key ( ) , value) ;
552+ }
553+ Ok ( out)
554+ }
555+ }
556+
557+ fn deep_utf8_lossy ( src : RawBson ) -> Result < Bson > {
558+ match src {
559+ RawBson :: Array ( arr) => {
560+ let mut tmp = vec ! [ ] ;
561+ for elem in arr. iter_elements ( ) {
562+ tmp. push ( deep_utf8_lossy ( elem?. value_utf8_lossy ( ) ?) ?) ;
563+ }
564+ Ok ( Bson :: Array ( tmp) )
565+ }
566+ RawBson :: Document ( doc) => {
567+ let mut tmp = doc ! { } ;
568+ for elem in doc. iter_elements ( ) {
569+ let elem = elem?;
570+ tmp. insert ( elem. key ( ) , deep_utf8_lossy ( elem. value_utf8_lossy ( ) ?) ?) ;
571+ }
572+ Ok ( Bson :: Document ( tmp) )
573+ }
574+ RawBson :: JavaScriptCodeWithScope ( RawJavaScriptCodeWithScope { code, scope } ) => {
575+ let mut tmp = doc ! { } ;
576+ for elem in scope. iter_elements ( ) {
577+ let elem = elem?;
578+ tmp. insert ( elem. key ( ) , deep_utf8_lossy ( elem. value_utf8_lossy ( ) ?) ?) ;
579+ }
580+ Ok ( Bson :: JavaScriptCodeWithScope ( JavaScriptCodeWithScope {
581+ code,
582+ scope : tmp,
583+ } ) )
584+ }
585+ v => v. try_into ( ) ,
548586 }
549587}
550588
0 commit comments