ordcode/
ord_ser.rs

1use crate::{Error, FormatVersion, buf::TailWriteBytes, Result,
2            params::{SerializerParams, LengthEncoder }};
3use crate::params::{AscendingOrder, PortableBinary, NativeBinary};
4use crate::primitives::SerializableValue;
5use serde::{ser, Serialize};
6
7/// `serde` serializer for binary data format which may preserve lexicographic ordering of values
8///
9/// The data format is customizable: you can choose lexicographic ordering for encoding
10/// of primitive types, endianness, encoding of lengths and enum discriminants; please see
11/// `SerializerParams` trait. This crate provides `params::AscendingOrder`, which is a default
12/// parameter set for `Serializer` which has the property to preserve lexicographic ordering
13/// of serialized values. To obtain the descending lexicographic ordering, the resulting byte buffer
14/// should be bitwise inverted, e.g. with `primitives::invert_buffer())`.
15///
16/// Serializer requires access to a double-ended data buffer, which should implement
17/// `WriteBytes` and `TailWriteBytes` traits. This crate provides a `DeWriteBuffer` type, which
18/// is a wrapper around a user-provided mutable slice to be used as a write buffer.
19///
20/// Serializer does not allocate anything: double-ended buffer should be big enough to contain
21/// serialized data. To know required buffer size in advance, please use `calc_size` with the same
22/// `SerializerParams`. Size calculation is cheap, for fixed-size structures it folds into
23/// compile-time constant.
24pub struct Serializer<W, P> {
25    writer: W,
26    params: P,
27}
28
29impl<W, P> Serializer<W, P>
30    where W: TailWriteBytes,
31          P: SerializerParams,
32{
33    pub fn new(writer: W, params: P) -> Self {
34        Self { writer, params }
35    }
36    pub fn into_writer(self) -> W { self.writer }
37
38    #[inline]
39    fn write_len(&mut self, v: usize) -> Result {
40        P::SeqLenEncoder::write(&mut self.writer, v)
41    }
42    fn write_discr(&mut self, v: u32) -> Result {
43        P::DiscriminantEncoder::write(&mut self.writer, v)
44    }
45}
46
47impl<W> FormatVersion<AscendingOrder> for Serializer<W, AscendingOrder>  {
48    const VERSION: u32 = 1;
49}
50
51impl<W> FormatVersion<PortableBinary> for Serializer<W, PortableBinary>  {
52    const VERSION: u32 = 1;
53}
54
55impl<W> FormatVersion<NativeBinary> for Serializer<W, NativeBinary>  {
56    const VERSION: u32 = 1;
57}
58
59macro_rules! serialize_fn {
60    ($fn:ident, $t:ty) => {
61        fn $fn(self, v: $t) -> Result {
62            v.to_writer(&mut self.writer, self.params)
63        }
64    }
65}
66
67impl<'a, W, P> ser::Serializer for &'a mut Serializer<W, P>
68    where W: TailWriteBytes,
69          P: SerializerParams,
70{
71    type Ok = ();
72    type Error = Error;
73
74    type SerializeSeq = SerializeCompoundSeq<'a, W, P>;
75    type SerializeTuple = SerializeCompound<'a, W, P>;
76    type SerializeTupleStruct = SerializeCompound<'a, W, P>;
77    type SerializeTupleVariant = SerializeCompound<'a, W, P>;
78    type SerializeMap = SerializeCompoundSeq<'a, W, P>;
79    type SerializeStruct = SerializeCompound<'a, W, P>;
80    type SerializeStructVariant = SerializeCompound<'a, W, P>;
81
82    serialize_fn!(serialize_bool, bool);
83    serialize_fn!(serialize_u8,   u8);
84    serialize_fn!(serialize_u16,  u16);
85    serialize_fn!(serialize_u32,  u32);
86    serialize_fn!(serialize_u64,  u64);
87    serialize_fn!(serialize_i8,   i8);
88    serialize_fn!(serialize_i16,  i16);
89    serialize_fn!(serialize_i32,  i32);
90    serialize_fn!(serialize_i64,  i64);
91    serialize_fn!(serialize_f32,  f32);
92    serialize_fn!(serialize_f64,  f64);
93    serde_if_integer128! {
94        serialize_fn!(serialize_u128,  u128);
95        serialize_fn!(serialize_i128,  i128);
96    }
97    serialize_fn!(serialize_char, char);
98
99    fn serialize_str(self, v: &str) -> Result {
100        self.serialize_bytes(v.as_ref())
101    }
102    fn serialize_bytes(self, v: &[u8]) -> Result {
103        self.write_len(v.len())?;
104        self.writer.write(&v)
105    }
106    fn serialize_none(self) -> Result {
107        self.serialize_u8(0)
108    }
109    fn serialize_some<T>(self, value: &T) -> Result
110        where T: ?Sized + Serialize,
111    {
112        self.serialize_u8(1)?;
113        value.serialize(self)
114    }
115    fn serialize_unit(self) -> Result { Ok(()) }
116
117    fn serialize_unit_struct(self, _name: &'static str) -> Result {
118        self.serialize_unit()
119    }
120    fn serialize_unit_variant(self, _name: &'static str, variant_index: u32,
121                              _variant: &'static str) -> Result {
122        self.write_discr(variant_index)
123    }
124    fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result
125        where T: ?Sized + Serialize,
126    {
127        value.serialize(self)
128    }
129    fn serialize_newtype_variant<T: ?Sized>(self, _name: &'static str,
130                                            variant_index: u32, _variant: &'static str,
131                                            value: &T) -> Result
132        where T: serde::ser::Serialize,
133    {
134        self.write_discr(variant_index)?;
135        value.serialize(self)
136    }
137
138    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
139        Ok(SerializeCompound::new(self))
140    }
141
142    fn serialize_tuple_struct(
143        self,
144        _name: &'static str,
145        _len: usize,
146    ) -> Result<Self::SerializeTupleStruct> {
147        Ok(SerializeCompound::new(self))
148    }
149
150    fn serialize_tuple_variant(
151        self,
152        _name: &'static str,
153        variant_index: u32,
154        _variant: &'static str,
155        _len: usize,
156    ) -> Result<Self::SerializeTupleVariant> {
157        self.write_discr(variant_index)?;
158        Ok(SerializeCompound::new(self))
159    }
160    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
161        Ok(SerializeCompound::new(self))
162    }
163    fn serialize_struct_variant(
164        self,
165        _name: &'static str,
166        variant_index: u32,
167        _variant: &'static str,
168        _len: usize,
169    ) -> Result<Self::SerializeStructVariant> {
170        self.write_discr(variant_index)?;
171        Ok(SerializeCompound::new(self))
172    }
173    // map and seq are variable-length sequences, use double encoding
174    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
175        let len = len.ok_or(Error::SerializeSequenceMustHaveLength)?;
176        SerializeCompoundSeq::new(len, self)
177    }
178    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> {
179        let len = len.ok_or(Error::SerializeSequenceMustHaveLength)?;
180        SerializeCompoundSeq::new(len, self)
181    }
182    #[cfg(not(feature = "std"))]
183    fn collect_str<T: ?Sized>(self, _value: &T) -> Result<Self::Ok, Self::Error> where
184        T: core::fmt::Display {
185        Err(Error::CannotSerializeDisplayInNoStdContext)
186    }
187}
188
189pub struct SerializeCompound<'a, W, P: SerializerParams> {
190    ser: &'a mut Serializer<W, P>,
191}
192
193impl <'a, W, P: SerializerParams> SerializeCompound<'a, W, P> {
194    fn new(ser: &'a mut Serializer<W, P>) -> Self {
195        Self { ser }
196    }
197}
198
199macro_rules! seq_compound_impl {
200    ($tn:ident, $fn:ident) => {
201        impl<'a, W, P> serde::ser::$tn for SerializeCompound<'a, W, P>
202            where W: TailWriteBytes,
203                  P: SerializerParams,
204        {
205            type Ok = ();
206            type Error = Error;
207
208            fn $fn<T: ?Sized>(&mut self, value: &T) -> Result
209                where T: serde::ser::Serialize,
210            {
211                value.serialize(&mut *self.ser)
212            }
213            fn end(self) -> Result {
214                Ok(())
215            }
216        }
217    }
218}
219
220seq_compound_impl!(SerializeSeq,   serialize_element);
221seq_compound_impl!(SerializeTuple, serialize_element);
222seq_compound_impl!(SerializeTupleStruct,  serialize_field);
223seq_compound_impl!(SerializeTupleVariant, serialize_field);
224
225macro_rules! struct_compound_impl {
226    ($tn:ident) => {
227        impl<'a, W, P> serde::ser::$tn for SerializeCompound<'a, W, P>
228            where W: TailWriteBytes,
229                  P: SerializerParams,
230        {
231            type Ok = ();
232            type Error = Error;
233
234            fn serialize_field<T: ?Sized>(&mut self, _key: &'static str, value: &T) -> Result
235                where T: serde::ser::Serialize,
236            {
237                value.serialize(&mut *self.ser)
238            }
239            fn end(self) -> Result {
240                Ok(())
241            }
242        }
243    }
244}
245
246struct_compound_impl!(SerializeStruct);
247struct_compound_impl!(SerializeStructVariant);
248
249pub struct SerializeCompoundSeq<'a, W, P: SerializerParams> {
250    ser: &'a mut Serializer<W, P>,
251}
252
253impl <'a, W, P> SerializeCompoundSeq<'a,  W, P>
254    where W: TailWriteBytes,
255          P: SerializerParams,
256{
257    fn new(len: usize, ser: &'a mut Serializer<W, P>) -> Result<Self> {
258        ser.write_len(len)?;
259        Ok(Self { ser })
260    }
261}
262
263macro_rules! serialize_seqitem {
264    ($fn:ident) => {
265        fn $fn<T: ?Sized>(&mut self, value: &T) -> Result
266            where T: serde::ser::Serialize,
267        {
268            value.serialize(&mut *self.ser)
269        }
270    }
271}
272
273impl<'a, W, P> serde::ser::SerializeSeq for SerializeCompoundSeq<'a, W, P>
274    where W: TailWriteBytes,
275          P: SerializerParams,
276{
277    type Ok = ();
278    type Error = Error;
279
280    serialize_seqitem!(serialize_element);
281    fn end(self) -> Result { Ok(()) }
282}
283
284impl<'a, W, P> serde::ser::SerializeMap for SerializeCompoundSeq<'a, W, P>
285    where W: TailWriteBytes,
286          P: SerializerParams,
287{
288    type Ok = ();
289    type Error = Error;
290
291    serialize_seqitem!(serialize_key);
292    serialize_seqitem!(serialize_value);
293    fn end(self) -> Result { Ok(()) }
294}