Skip to content

Commit 3df66fd

Browse files
committed
recursion
1 parent 04c1c35 commit 3df66fd

File tree

3 files changed

+44
-4
lines changed

3 files changed

+44
-4
lines changed

src/raw/array.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,11 @@ impl RawArray {
221221
pub fn is_empty(&self) -> bool {
222222
self.doc.is_empty()
223223
}
224+
225+
/// Returns an iterator over the `RawElement`s in the array.
226+
pub fn iter_elements(&self) -> RawIter {
227+
RawIter::new(&self.doc)
228+
}
224229
}
225230

226231
impl std::fmt::Debug for RawArray {

src/raw/iter.rs

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,11 @@ use crate::{
99
DateTime,
1010
Decimal128,
1111
RawArray,
12+
RawArrayBuf,
1213
RawBinaryRef,
1314
RawBson,
1415
RawDbPointerRef,
16+
RawDocumentBuf,
1517
RawJavaScriptCodeWithScopeRef,
1618
RawRegexRef,
1719
Timestamp,
@@ -268,8 +270,41 @@ impl<'a> RawElement<'a> {
268270

269271
pub fn value_utf8_lossy(&self) -> Result<RawBson> {
270272
match self.value_utf8_lossy_inner()? {
271-
Some(v) => Ok(v.into()),
272-
None => Ok(self.value()?.to_raw_bson()),
273+
Some(v) => Ok(match v {
274+
Utf8LossyBson::JavaScriptCodeWithScope(Utf8LossyJavaScriptCodeWithScope {
275+
code,
276+
scope,
277+
}) => {
278+
let mut tmp = RawDocumentBuf::new();
279+
for elem in scope.iter_elements() {
280+
let elem = elem?;
281+
tmp.append(elem.key(), elem.value_utf8_lossy()?);
282+
}
283+
RawBson::JavaScriptCodeWithScope(super::RawJavaScriptCodeWithScope {
284+
code,
285+
scope: tmp,
286+
})
287+
}
288+
v => v.into(),
289+
}),
290+
None => Ok(match self.value()? {
291+
RawBsonRef::Array(arr) => {
292+
let mut tmp = RawArrayBuf::new();
293+
for elem in arr.iter_elements() {
294+
tmp.push(elem?.value_utf8_lossy()?);
295+
}
296+
RawBson::Array(tmp)
297+
}
298+
RawBsonRef::Document(doc) => {
299+
let mut tmp = RawDocumentBuf::new();
300+
for elem in doc.iter_elements() {
301+
let elem = elem?;
302+
tmp.append(elem.key(), elem.value_utf8_lossy()?);
303+
}
304+
RawBson::Document(tmp)
305+
}
306+
v => v.to_raw_bson(),
307+
}),
273308
}
274309
}
275310

src/tests/modules/serializer_deserializer.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,12 +68,12 @@ fn test_encode_decode_utf8_string_invalid() {
6868
let bytes = b"\x80\xae".to_vec();
6969
let src = unsafe { String::from_utf8_unchecked(bytes) };
7070

71-
let doc = doc! { "key": src };
71+
let doc = doc! { "key": &src, "subdoc": { "subkey": &src } };
7272

7373
let mut buf = Vec::new();
7474
doc.to_writer(&mut buf).unwrap();
7575

76-
let expected = doc! { "key": "��" };
76+
let expected = doc! { "key": "��", "subdoc": { "subkey": "��" } };
7777
let decoded = RawDocumentBuf::from_reader(&mut Cursor::new(buf))
7878
.unwrap()
7979
.to_document_utf8_lossy()

0 commit comments

Comments
 (0)