Skip to content

Commit b202364

Browse files
authored
RUST-1062 More efficiently serialize array indexes (#384)
1 parent d499e64 commit b202364

File tree

1 file changed

+26
-7
lines changed

1 file changed

+26
-7
lines changed

src/ser/raw/document_serializer.rs

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -30,17 +30,29 @@ impl<'a> DocumentSerializer<'a> {
3030
})
3131
}
3232

33+
/// Serialize a document key using the provided closure.
34+
fn serialize_doc_key_custom<F: FnOnce(&mut Serializer) -> Result<()>>(
35+
&mut self,
36+
f: F,
37+
) -> Result<()> {
38+
// push a dummy element type for now, will update this once we serialize the value
39+
self.root_serializer.reserve_element_type();
40+
f(self.root_serializer)?;
41+
self.num_keys_serialized += 1;
42+
Ok(())
43+
}
44+
45+
/// Serialize a document key to string using `KeySerializer`.
3346
fn serialize_doc_key<T>(&mut self, key: &T) -> Result<()>
3447
where
3548
T: serde::Serialize + ?Sized,
3649
{
37-
// push a dummy element type for now, will update this once we serialize the value
38-
self.root_serializer.reserve_element_type();
39-
key.serialize(KeySerializer {
40-
root_serializer: &mut *self.root_serializer,
50+
self.serialize_doc_key_custom(|rs| {
51+
key.serialize(KeySerializer {
52+
root_serializer: rs,
53+
})?;
54+
Ok(())
4155
})?;
42-
43-
self.num_keys_serialized += 1;
4456
Ok(())
4557
}
4658

@@ -63,7 +75,13 @@ impl<'a> serde::ser::SerializeSeq for DocumentSerializer<'a> {
6375
where
6476
T: serde::Serialize,
6577
{
66-
self.serialize_doc_key(&self.num_keys_serialized.to_string())?;
78+
let index = self.num_keys_serialized;
79+
self.serialize_doc_key_custom(|rs| {
80+
use std::io::Write;
81+
write!(&mut rs.bytes, "{}", index)?;
82+
rs.bytes.push(0);
83+
Ok(())
84+
})?;
6785
value.serialize(&mut *self.root_serializer)
6886
}
6987

@@ -160,6 +178,7 @@ impl<'a> serde::ser::SerializeTupleStruct for DocumentSerializer<'a> {
160178
}
161179

162180
/// Serializer used specifically for serializing document keys.
181+
/// Only keys that serialize to strings will be accepted.
163182
struct KeySerializer<'a> {
164183
root_serializer: &'a mut Serializer,
165184
}

0 commit comments

Comments
 (0)