serde_v2/
ser.rs

1//! Serde serializer for [stratum v2][Sv2] implemented following [serde tutorial][tutorial]
2//!
3//! Right now trying to serialize a value that is an invalid Sv2 type will result in a panic so
4//! error are catched as soon as possible.
5//!
6//! [Sv2]: https://docs.google.com/document/d/1FadCWj-57dvhxsnFM_7X806qyvhR0u3i85607bGHxvg/edit
7//! [tutorial]: https://serde.rs/data-format.html
8//!
9use crate::error::{Error, Result};
10use serde::{ser, Serialize};
11
12pub struct Serializer<W: std::io::Write> {
13    output: W,
14}
15
16pub fn to_bytes<T>(value: &T) -> Result<Vec<u8>>
17where
18    T: Serialize,
19{
20    let output: Vec<u8> = vec![];
21    let mut serializer = Serializer { output };
22    value.serialize(&mut serializer)?;
23    Ok(serializer.output)
24}
25
26pub fn to_writer<T, W: std::io::Write>(value: &T, writer: W) -> Result<()>
27where
28    T: Serialize,
29{
30    let mut serializer = Serializer { output: writer };
31    value.serialize(&mut serializer)?;
32    Ok(())
33}
34
35impl<'a, W: std::io::Write> ser::Serializer for &'a mut Serializer<W> {
36    type Ok = ();
37
38    type Error = Error;
39
40    // Associated types for keeping track of additional state while serializing
41    // compound data structures like sequences and maps. In this case no
42    // additional state is required beyond what is already stored in the
43    // Serializer struct.
44    type SerializeSeq = Self;
45    type SerializeTuple = Self;
46    type SerializeTupleStruct = Self;
47    type SerializeTupleVariant = Self;
48    type SerializeMap = Self;
49    type SerializeStruct = Self;
50    type SerializeStructVariant = Self;
51
52    // TODO check endianess
53    fn serialize_bool(self, v: bool) -> Result<()> {
54        match v {
55            true => self.output.write_all(&[1]).map_err(|_| Error::WriteError)?,
56            false => self.output.write_all(&[0]).map_err(|_| Error::WriteError)?,
57        };
58        Ok(())
59    }
60
61    fn serialize_u8(self, v: u8) -> Result<()> {
62        self.output.write_all(&[v]).map_err(|_| Error::WriteError)
63    }
64
65    fn serialize_u16(self, v: u16) -> Result<()> {
66        self.output
67            .write_all(&v.to_le_bytes())
68            .map_err(|_| Error::WriteError)
69    }
70
71    fn serialize_u32(self, v: u32) -> Result<()> {
72        self.output
73            .write_all(&v.to_le_bytes())
74            .map_err(|_| Error::WriteError)
75    }
76
77    // Serialize string to STR0_255
78    fn serialize_str(self, v: &str) -> Result<()> {
79        match v.len() {
80            l @ 0..=255 => {
81                self.output
82                    .write_all(&[l as u8])
83                    .map_err(|_| Error::WriteError)?;
84            }
85            _ => return Err(Error::StringLenBiggerThan256),
86        };
87        self.output
88            .write_all(&v.as_bytes())
89            .map_err(|_| Error::WriteError)
90    }
91
92    fn serialize_bytes(self, v: &[u8]) -> Result<()> {
93        self.output.write_all(v).map_err(|_| Error::WriteError)
94    }
95
96    // As is done here, serializers are encouraged to treat newtype structs as
97    // insignificant wrappers around the data they contain.
98    fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<()>
99    where
100        T: ?Sized + Serialize,
101    {
102        value.serialize(self)
103    }
104
105    // serialize_struct should preserve field order TODO verify it
106    // https://users.rust-lang.org/t/order-of-fields-in-serde-json-to-string/48928/3?u=fi3
107    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
108        Ok(self)
109    }
110
111    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
112        Ok(self)
113    }
114
115    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
116        Ok(self)
117    }
118
119    ///// UNIMPLEMENTED /////
120
121    fn serialize_i8(self, _v: i8) -> Result<()> {
122        todo!()
123    }
124
125    fn serialize_i16(self, _v: i16) -> Result<()> {
126        todo!()
127    }
128
129    fn serialize_i32(self, _v: i32) -> Result<()> {
130        todo!()
131    }
132
133    fn serialize_i64(self, _v: i64) -> Result<()> {
134        todo!()
135    }
136
137    fn serialize_u64(self, _v: u64) -> Result<()> {
138        todo!()
139    }
140
141    fn serialize_f32(self, _v: f32) -> Result<()> {
142        todo!()
143    }
144
145    fn serialize_f64(self, _v: f64) -> Result<()> {
146        todo!()
147    }
148
149    fn serialize_char(self, _v: char) -> Result<()> {
150        todo!()
151    }
152
153    fn serialize_none(self) -> Result<()> {
154        todo!()
155    }
156
157    fn serialize_some<T>(self, _value: &T) -> Result<()>
158    where
159        T: ?Sized + Serialize,
160    {
161        todo!()
162    }
163
164    fn serialize_unit(self) -> Result<()> {
165        todo!()
166    }
167
168    fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
169        todo!()
170    }
171
172    fn serialize_unit_variant(
173        self,
174        _name: &'static str,
175        _variant_index: u32,
176        _variant: &'static str,
177    ) -> Result<()> {
178        todo!()
179    }
180
181    fn serialize_newtype_variant<T>(
182        self,
183        _name: &'static str,
184        _variant_index: u32,
185        _variant: &'static str,
186        _value: &T,
187    ) -> Result<()>
188    where
189        T: ?Sized + Serialize,
190    {
191        todo!()
192    }
193
194    fn serialize_tuple_struct(
195        self,
196        _name: &'static str,
197        _len: usize,
198    ) -> Result<Self::SerializeTupleStruct> {
199        todo!()
200    }
201
202    fn serialize_tuple_variant(
203        self,
204        _name: &'static str,
205        _variant_index: u32,
206        _variant: &'static str,
207        _len: usize,
208    ) -> Result<Self::SerializeTupleVariant> {
209        todo!()
210    }
211
212    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
213        todo!()
214    }
215
216    fn serialize_struct_variant(
217        self,
218        _name: &'static str,
219        _variant_index: u32,
220        _variant: &'static str,
221        _len: usize,
222    ) -> Result<Self::SerializeStructVariant> {
223        todo!()
224    }
225}
226
227impl<'a, W: std::io::Write> ser::SerializeStruct for &'a mut Serializer<W> {
228    type Ok = ();
229    type Error = Error;
230
231    fn serialize_field<T>(&mut self, _key: &'static str, value: &T) -> Result<()>
232    where
233        T: ?Sized + Serialize,
234    {
235        value.serialize(&mut **self)
236    }
237
238    fn end(self) -> Result<()> {
239        Ok(())
240    }
241}
242
243// TODO check if usefull and in case disimplement it!
244impl<'a, W: std::io::Write> ser::SerializeSeq for &'a mut Serializer<W> {
245    type Ok = ();
246    type Error = Error;
247
248    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
249    where
250        T: ?Sized + Serialize,
251    {
252        value.serialize(&mut **self)
253    }
254
255    fn end(self) -> Result<()> {
256        Ok(())
257    }
258}
259
260impl<'a, W: std::io::Write> ser::SerializeTuple for &'a mut Serializer<W> {
261    type Ok = ();
262    type Error = Error;
263
264    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
265    where
266        T: ?Sized + Serialize,
267    {
268        value.serialize(&mut **self)
269    }
270
271    fn end(self) -> Result<()> {
272        Ok(())
273    }
274}
275
276///// UNIMPLEMENTED /////
277
278impl<'a, W: std::io::Write> ser::SerializeTupleStruct for &'a mut Serializer<W> {
279    type Ok = ();
280    type Error = Error;
281
282    fn serialize_field<T>(&mut self, _value: &T) -> Result<()>
283    where
284        T: ?Sized + Serialize,
285    {
286        todo!()
287    }
288
289    fn end(self) -> Result<()> {
290        todo!()
291    }
292}
293
294impl<'a, W: std::io::Write> ser::SerializeTupleVariant for &'a mut Serializer<W> {
295    type Ok = ();
296    type Error = Error;
297
298    fn serialize_field<T>(&mut self, _value: &T) -> Result<()>
299    where
300        T: ?Sized + Serialize,
301    {
302        todo!()
303    }
304
305    fn end(self) -> Result<()> {
306        todo!()
307    }
308}
309
310impl<'a, W: std::io::Write> ser::SerializeMap for &'a mut Serializer<W> {
311    type Ok = ();
312    type Error = Error;
313
314    fn serialize_key<T>(&mut self, _key: &T) -> Result<()>
315    where
316        T: ?Sized + Serialize,
317    {
318        todo!()
319    }
320
321    fn serialize_value<T>(&mut self, _value: &T) -> Result<()>
322    where
323        T: ?Sized + Serialize,
324    {
325        todo!()
326    }
327
328    fn end(self) -> Result<()> {
329        todo!()
330    }
331}
332
333impl<'a, W: std::io::Write> ser::SerializeStructVariant for &'a mut Serializer<W> {
334    type Ok = ();
335    type Error = Error;
336
337    fn serialize_field<T>(&mut self, _key: &'static str, _value: &T) -> Result<()>
338    where
339        T: ?Sized + Serialize,
340    {
341        todo!()
342    }
343
344    fn end(self) -> Result<()> {
345        todo!()
346    }
347}
348
349///// TEST /////
350
351#[test]
352fn test_struct() {
353    #[derive(Serialize)]
354    struct Test {
355        a: u32,
356        b: u8,
357    }
358
359    let test = Test { a: 456, b: 9 };
360    let expected = vec![200, 1, 0, 0, 9];
361    assert_eq!(to_bytes(&test).unwrap(), expected);
362}