Skip to content

Commit 93b391c

Browse files
RUST-2258 Use borrowed buffer in raw serializer (#590)
Co-authored-by: Isabel Atkinson <isabel.atkinson@mongodb.com>
1 parent e76c0e7 commit 93b391c

File tree

5 files changed

+97
-80
lines changed

5 files changed

+97
-80
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -474,6 +474,7 @@ pub use self::{
474474
},
475475
ser::{
476476
serialize_to_bson,
477+
serialize_to_buffer,
477478
serialize_to_document,
478479
serialize_to_raw_document_buf,
479480
serialize_to_vec,

src/ser.rs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,19 @@ pub fn serialize_to_vec<T>(value: &T) -> Result<Vec<u8>>
8989
where
9090
T: Serialize,
9191
{
92-
let mut serializer = raw::Serializer::new();
92+
let mut bytes = Vec::new();
93+
serialize_to_buffer(value, &mut bytes)?;
94+
Ok(bytes)
95+
}
96+
97+
/// Serialize the given `T` as a BSON byte vector into the provided byte buffer.
98+
/// This allows reusing the same buffer for multiple serializations.
99+
#[inline]
100+
pub fn serialize_to_buffer<T>(value: &T, buffer: &mut Vec<u8>) -> Result<()>
101+
where
102+
T: Serialize,
103+
{
104+
let mut serializer = raw::Serializer::new(buffer);
93105
#[cfg(feature = "serde_path_to_error")]
94106
{
95107
serde_path_to_error::serialize(value, &mut serializer).map_err(Error::with_path)?;
@@ -98,7 +110,7 @@ where
98110
{
99111
value.serialize(&mut serializer)?;
100112
}
101-
Ok(serializer.into_vec())
113+
Ok(())
102114
}
103115

104116
/// Serialize the given `T` as a [`RawDocumentBuf`].

src/ser/raw.rs

Lines changed: 39 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,11 @@ use crate::{
2222
use document_serializer::DocumentSerializer;
2323

2424
/// Serializer used to convert a type `T` into raw BSON bytes.
25-
pub(crate) struct Serializer {
26-
bytes: Vec<u8>,
25+
pub(crate) struct Serializer<'a> {
26+
bytes: &'a mut Vec<u8>,
27+
28+
/// The index into `bytes` where the current serialization started.
29+
start_index: usize,
2730

2831
/// The index into `bytes` where the current element type will need to be stored.
2932
/// This needs to be set retroactively because in BSON, the element type comes before the key,
@@ -58,21 +61,18 @@ impl SerializerHint {
5861
}
5962
}
6063

61-
impl Serializer {
62-
pub(crate) fn new() -> Self {
64+
impl<'a> Serializer<'a> {
65+
pub(crate) fn new(bytes: &'a mut Vec<u8>) -> Self {
66+
let start_index = bytes.len();
6367
Self {
64-
bytes: Vec::new(),
65-
type_index: 0,
68+
bytes,
69+
start_index,
70+
type_index: start_index,
6671
hint: SerializerHint::None,
6772
human_readable: false,
6873
}
6974
}
7075

71-
/// Convert this serializer into the vec of the serialized bytes.
72-
pub(crate) fn into_vec(self) -> Vec<u8> {
73-
self.bytes
74-
}
75-
7676
/// Reserve a spot for the element type to be set retroactively via `update_element_type`.
7777
#[inline]
7878
fn reserve_element_type(&mut self) {
@@ -83,7 +83,7 @@ impl Serializer {
8383
/// Retroactively set the element type of the most recently serialized element.
8484
#[inline]
8585
fn update_element_type(&mut self, t: ElementType) -> Result<()> {
86-
if self.type_index == 0 {
86+
if self.type_index == self.start_index {
8787
if matches!(t, ElementType::EmbeddedDocument) {
8888
// don't need to set the element type for the top level document
8989
return Ok(());
@@ -108,22 +108,22 @@ impl Serializer {
108108

109109
fn serialize_raw(&mut self, v: RawBsonRef) -> Result<()> {
110110
self.update_element_type(v.element_type())?;
111-
v.append_to(&mut self.bytes);
111+
v.append_to(self.bytes);
112112
Ok(())
113113
}
114114
}
115115

116-
impl<'a> serde::Serializer for &'a mut Serializer {
116+
impl<'a, 'b> serde::Serializer for &'a mut Serializer<'b> {
117117
type Ok = ();
118118
type Error = Error;
119119

120-
type SerializeSeq = DocumentSerializer<'a>;
121-
type SerializeTuple = DocumentSerializer<'a>;
122-
type SerializeTupleStruct = DocumentSerializer<'a>;
123-
type SerializeTupleVariant = VariantSerializer<'a>;
124-
type SerializeMap = DocumentSerializer<'a>;
125-
type SerializeStruct = StructSerializer<'a>;
126-
type SerializeStructVariant = VariantSerializer<'a>;
120+
type SerializeSeq = DocumentSerializer<'a, 'b>;
121+
type SerializeTuple = DocumentSerializer<'a, 'b>;
122+
type SerializeTupleStruct = DocumentSerializer<'a, 'b>;
123+
type SerializeTupleVariant = VariantSerializer<'a, 'b>;
124+
type SerializeMap = DocumentSerializer<'a, 'b>;
125+
type SerializeStruct = StructSerializer<'a, 'b>;
126+
type SerializeStructVariant = VariantSerializer<'a, 'b>;
127127

128128
fn is_human_readable(&self) -> bool {
129129
self.human_readable
@@ -385,15 +385,15 @@ impl<'a> serde::Serializer for &'a mut Serializer {
385385
}
386386
}
387387

388-
pub(crate) enum StructSerializer<'a> {
388+
pub(crate) enum StructSerializer<'a, 'b> {
389389
/// Serialize a BSON value currently represented in serde as a struct (e.g. ObjectId)
390-
Value(ValueSerializer<'a>),
390+
Value(ValueSerializer<'a, 'b>),
391391

392392
/// Serialize the struct as a document.
393-
Document(DocumentSerializer<'a>),
393+
Document(DocumentSerializer<'a, 'b>),
394394
}
395395

396-
impl SerializeStruct for StructSerializer<'_> {
396+
impl SerializeStruct for StructSerializer<'_, '_> {
397397
type Ok = ();
398398
type Error = Error;
399399

@@ -424,8 +424,8 @@ enum VariantInnerType {
424424

425425
/// Serializer used for enum variants, including both tuple (e.g. Foo::Bar(1, 2, 3)) and
426426
/// struct (e.g. Foo::Bar { a: 1 }).
427-
pub(crate) struct VariantSerializer<'a> {
428-
root_serializer: &'a mut Serializer,
427+
pub(crate) struct VariantSerializer<'a, 'b> {
428+
root_serializer: &'a mut Serializer<'b>,
429429

430430
/// Variants are serialized as documents of the form `{ <variant name>: <document or array> }`,
431431
/// and `doc_start` indicates the index at which the outer document begins.
@@ -438,22 +438,26 @@ pub(crate) struct VariantSerializer<'a> {
438438
num_elements_serialized: usize,
439439
}
440440

441-
impl<'a> VariantSerializer<'a> {
442-
fn start(rs: &'a mut Serializer, variant: &'static CStr, inner_type: VariantInnerType) -> Self {
441+
impl<'a, 'b> VariantSerializer<'a, 'b> {
442+
fn start(
443+
rs: &'a mut Serializer<'b>,
444+
variant: &'static CStr,
445+
inner_type: VariantInnerType,
446+
) -> Self {
443447
let doc_start = rs.bytes.len();
444448
// write placeholder length for document, will be updated at end
445449
static ZERO: RawBsonRef = RawBsonRef::Int32(0);
446-
ZERO.append_to(&mut rs.bytes);
450+
ZERO.append_to(rs.bytes);
447451

448452
let inner = match inner_type {
449453
VariantInnerType::Struct => ElementType::EmbeddedDocument,
450454
VariantInnerType::Tuple => ElementType::Array,
451455
};
452456
rs.bytes.push(inner as u8);
453-
variant.append_to(&mut rs.bytes);
457+
variant.append_to(rs.bytes);
454458
let inner_start = rs.bytes.len();
455459
// write placeholder length for inner, will be updated at end
456-
ZERO.append_to(&mut rs.bytes);
460+
ZERO.append_to(rs.bytes);
457461

458462
Self {
459463
root_serializer: rs,
@@ -469,7 +473,7 @@ impl<'a> VariantSerializer<'a> {
469473
T: Serialize + ?Sized,
470474
{
471475
self.root_serializer.reserve_element_type();
472-
CStr::from_str(k)?.append_to(&mut self.root_serializer.bytes);
476+
CStr::from_str(k)?.append_to(self.root_serializer.bytes);
473477
v.serialize(&mut *self.root_serializer)?;
474478

475479
self.num_elements_serialized += 1;
@@ -492,7 +496,7 @@ impl<'a> VariantSerializer<'a> {
492496
}
493497
}
494498

495-
impl serde::ser::SerializeTupleVariant for VariantSerializer<'_> {
499+
impl serde::ser::SerializeTupleVariant for VariantSerializer<'_, '_> {
496500
type Ok = ();
497501

498502
type Error = Error;
@@ -511,7 +515,7 @@ impl serde::ser::SerializeTupleVariant for VariantSerializer<'_> {
511515
}
512516
}
513517

514-
impl serde::ser::SerializeStructVariant for VariantSerializer<'_> {
518+
impl serde::ser::SerializeStructVariant for VariantSerializer<'_, '_> {
515519
type Ok = ();
516520

517521
type Error = Error;

src/ser/raw/document_serializer.rs

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -7,21 +7,21 @@ use crate::{
77

88
use super::Serializer;
99

10-
pub(crate) struct DocumentSerializationResult<'a> {
11-
pub(crate) root_serializer: &'a mut Serializer,
10+
pub(crate) struct DocumentSerializationResult<'a, 'b> {
11+
pub(crate) root_serializer: &'a mut Serializer<'b>,
1212
}
1313

1414
/// Serializer used to serialize document or array bodies.
15-
pub(crate) struct DocumentSerializer<'a> {
16-
root_serializer: &'a mut Serializer,
15+
pub(crate) struct DocumentSerializer<'a, 'b> {
16+
root_serializer: &'a mut Serializer<'b>,
1717
num_keys_serialized: usize,
1818
start: usize,
1919
}
2020

21-
impl<'a> DocumentSerializer<'a> {
22-
pub(crate) fn start(rs: &'a mut Serializer) -> Self {
21+
impl<'a, 'b> DocumentSerializer<'a, 'b> {
22+
pub(crate) fn start(rs: &'a mut Serializer<'b>) -> Self {
2323
let start = rs.bytes.len();
24-
RawBsonRef::Int32(0).append_to(&mut rs.bytes);
24+
RawBsonRef::Int32(0).append_to(rs.bytes);
2525
Self {
2626
root_serializer: rs,
2727
num_keys_serialized: 0,
@@ -30,7 +30,7 @@ impl<'a> DocumentSerializer<'a> {
3030
}
3131

3232
/// Serialize a document key using the provided closure.
33-
fn serialize_doc_key_custom<F: FnOnce(&mut Serializer) -> Result<()>>(
33+
fn serialize_doc_key_custom<F: FnOnce(&mut Serializer<'b>) -> Result<()>>(
3434
&mut self,
3535
f: F,
3636
) -> Result<()> {
@@ -55,7 +55,7 @@ impl<'a> DocumentSerializer<'a> {
5555
Ok(())
5656
}
5757

58-
pub(crate) fn end_doc(self) -> crate::ser::Result<DocumentSerializationResult<'a>> {
58+
pub(crate) fn end_doc(self) -> crate::ser::Result<DocumentSerializationResult<'a, 'b>> {
5959
self.root_serializer.bytes.push(0);
6060
let length = (self.root_serializer.bytes.len() - self.start) as i32;
6161
self.root_serializer.replace_i32(self.start, length);
@@ -65,7 +65,7 @@ impl<'a> DocumentSerializer<'a> {
6565
}
6666
}
6767

68-
impl serde::ser::SerializeSeq for DocumentSerializer<'_> {
68+
impl serde::ser::SerializeSeq for DocumentSerializer<'_, '_> {
6969
type Ok = ();
7070
type Error = Error;
7171

@@ -90,7 +90,7 @@ impl serde::ser::SerializeSeq for DocumentSerializer<'_> {
9090
}
9191
}
9292

93-
impl serde::ser::SerializeMap for DocumentSerializer<'_> {
93+
impl serde::ser::SerializeMap for DocumentSerializer<'_, '_> {
9494
type Ok = ();
9595

9696
type Error = Error;
@@ -116,7 +116,7 @@ impl serde::ser::SerializeMap for DocumentSerializer<'_> {
116116
}
117117
}
118118

119-
impl serde::ser::SerializeStruct for DocumentSerializer<'_> {
119+
impl serde::ser::SerializeStruct for DocumentSerializer<'_, '_> {
120120
type Ok = ();
121121

122122
type Error = Error;
@@ -136,7 +136,7 @@ impl serde::ser::SerializeStruct for DocumentSerializer<'_> {
136136
}
137137
}
138138

139-
impl serde::ser::SerializeTuple for DocumentSerializer<'_> {
139+
impl serde::ser::SerializeTuple for DocumentSerializer<'_, '_> {
140140
type Ok = ();
141141

142142
type Error = Error;
@@ -156,7 +156,7 @@ impl serde::ser::SerializeTuple for DocumentSerializer<'_> {
156156
}
157157
}
158158

159-
impl serde::ser::SerializeTupleStruct for DocumentSerializer<'_> {
159+
impl serde::ser::SerializeTupleStruct for DocumentSerializer<'_, '_> {
160160
type Ok = ();
161161

162162
type Error = Error;
@@ -178,11 +178,11 @@ impl serde::ser::SerializeTupleStruct for DocumentSerializer<'_> {
178178

179179
/// Serializer used specifically for serializing document keys.
180180
/// Only keys that serialize to strings will be accepted.
181-
struct KeySerializer<'a> {
182-
root_serializer: &'a mut Serializer,
181+
struct KeySerializer<'a, 'b> {
182+
root_serializer: &'a mut Serializer<'b>,
183183
}
184184

185-
impl serde::Serializer for KeySerializer<'_> {
185+
impl serde::Serializer for KeySerializer<'_, '_> {
186186
type Ok = ();
187187

188188
type Error = Error;
@@ -257,7 +257,7 @@ impl serde::Serializer for KeySerializer<'_> {
257257

258258
#[inline]
259259
fn serialize_str(self, v: &str) -> Result<Self::Ok> {
260-
crate::raw::CStr::from_str(v)?.append_to(&mut self.root_serializer.bytes);
260+
crate::raw::CStr::from_str(v)?.append_to(self.root_serializer.bytes);
261261
Ok(())
262262
}
263263

0 commit comments

Comments
 (0)