rust_openttd_admin/packet/serde/
ser.rs

1use super::error::{Error, Result};
2use byteorder::{ByteOrder, LittleEndian, WriteBytesExt};
3use serde::ser::{self, Impossible, Serialize, SerializeSeq};
4use std::io::Write;
5
6#[derive(Clone, Eq, PartialEq)]
7struct Serializer {
8    output: Vec<u8>,
9    /// Indicates an option was serialized, if it was no more input is allowed.
10    serialized_option: bool,
11}
12
13impl Serializer {
14    /// Checks whether the serializer can accept more input and returns an
15    /// error otherwise.
16    fn check_can_serialize_more(&self) -> Result<()> {
17        if self.serialized_option {
18            Err(Error::InvalidOption)
19        } else {
20            Ok(())
21        }
22    }
23}
24
25pub trait WritablePacket: Serialize {
26    const PACKET_TYPE: u8;
27}
28
29pub trait PacketWrite<T: WritablePacket> {
30    fn write_packet(&mut self, value: &T) -> Result<()>;
31}
32
33impl<T: WritablePacket, W: std::io::Write> PacketWrite<T> for W {
34    fn write_packet(&mut self, value: &T) -> Result<()> {
35        let mut serializer = Serializer {
36            output: vec![0, 0, T::PACKET_TYPE],
37            serialized_option: false,
38        };
39        value.serialize(&mut serializer)?;
40        let length = serializer.output.len() as u16;
41        LittleEndian::write_u16(&mut serializer.output[0..2], length);
42        self.write_all(&serializer.output)?;
43        Ok(())
44    }
45}
46
47impl<'a> ser::Serializer for &'a mut Serializer {
48    type Ok = ();
49    type Error = Error;
50
51    type SerializeTuple = Self;
52    type SerializeSeq = Self;
53    type SerializeTupleStruct = Self;
54    type SerializeStruct = Self;
55
56    type SerializeTupleVariant = Impossible<(), Error>;
57    type SerializeMap = Impossible<(), Error>;
58    type SerializeStructVariant = Impossible<(), Error>;
59
60    fn serialize_bool(self, v: bool) -> Result<()> {
61        self.check_can_serialize_more()?;
62        self.output.write_u8(if v { 1 } else { 0 })?;
63        Ok(())
64    }
65
66    fn serialize_i8(self, v: i8) -> Result<()> {
67        self.check_can_serialize_more()?;
68        self.output.write_i8(v)?;
69        Ok(())
70    }
71
72    fn serialize_u8(self, v: u8) -> Result<()> {
73        self.check_can_serialize_more()?;
74        self.output.write_u8(v)?;
75        Ok(())
76    }
77
78    fn serialize_i16(self, v: i16) -> Result<()> {
79        self.check_can_serialize_more()?;
80        self.output.write_i16::<LittleEndian>(v)?;
81        Ok(())
82    }
83
84    fn serialize_u16(self, v: u16) -> Result<()> {
85        self.check_can_serialize_more()?;
86        self.output.write_u16::<LittleEndian>(v)?;
87        Ok(())
88    }
89
90    fn serialize_i32(self, v: i32) -> Result<()> {
91        self.check_can_serialize_more()?;
92        self.output.write_i32::<LittleEndian>(v)?;
93        Ok(())
94    }
95
96    fn serialize_u32(self, v: u32) -> Result<()> {
97        self.check_can_serialize_more()?;
98        self.output.write_u32::<LittleEndian>(v)?;
99        Ok(())
100    }
101
102    fn serialize_i64(self, v: i64) -> Result<()> {
103        self.check_can_serialize_more()?;
104        self.output.write_i64::<LittleEndian>(v)?;
105        Ok(())
106    }
107
108    fn serialize_u64(self, v: u64) -> Result<()> {
109        self.check_can_serialize_more()?;
110        self.output.write_u64::<LittleEndian>(v)?;
111        Ok(())
112    }
113
114    fn serialize_f32(self, v: f32) -> Result<()> {
115        self.check_can_serialize_more()?;
116        self.output.write_f32::<LittleEndian>(v)?;
117        Ok(())
118    }
119
120    fn serialize_f64(self, v: f64) -> Result<()> {
121        self.check_can_serialize_more()?;
122        self.output.write_f64::<LittleEndian>(v)?;
123        Ok(())
124    }
125
126    fn serialize_char(self, v: char) -> Result<()> {
127        // Serialize a char as a string.
128        self.serialize_str(&v.to_string())
129    }
130
131    fn serialize_str(self, s: &str) -> Result<()> {
132        self.check_can_serialize_more()?;
133        self.output.write_all(s.as_bytes())?;
134        self.output.write_u8(0)?;
135        Ok(())
136    }
137
138    fn serialize_bytes(self, v: &[u8]) -> Result<()> {
139        self.check_can_serialize_more()?;
140        // Serialize bytes as a u8 sequence.
141        let mut seq = self.serialize_seq(Some(v.len()))?;
142        for b in v {
143            seq.serialize_element(b)?;
144        }
145        seq.end()
146    }
147
148    fn serialize_none(self) -> Result<()> {
149        // None is denoted by EOF. Because of this, we don't write anything,
150        // but we need to make sure nothing more is written.
151        self.serialized_option = true;
152        Ok(())
153    }
154
155    fn serialize_some<T>(self, v: &T) -> Result<()>
156    where
157        T: ?Sized + Serialize,
158    {
159        // Since None is denoted by EOF, we serialize Some by just writing the
160        // inner data. We do set the flag to make sure nothing more is written.
161        v.serialize(&mut *self)?;
162        self.serialized_option = true;
163        Ok(())
164    }
165
166    fn serialize_unit(self) -> Result<()> {
167        Ok(())
168    }
169
170    fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
171        Ok(())
172    }
173
174    fn serialize_unit_variant(
175        self,
176        _name: &'static str,
177        _variant_index: u32,
178        _variant: &'static str,
179    ) -> Result<()> {
180        // An unit variant should provide their own implementation since the
181        // serialized size could differ.
182        Err(Error::NotSupported)
183    }
184
185    fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<()>
186    where
187        T: ?Sized + Serialize,
188    {
189        // Just serialize the inner data.
190        value.serialize(self)
191    }
192
193    fn serialize_newtype_variant<T>(
194        self,
195        _name: &'static str,
196        _variant_index: u32,
197        _variant: &'static str,
198        _value: &T,
199    ) -> Result<()>
200    where
201        T: ?Sized + Serialize,
202    {
203        // A variant should provide their own implementation since the
204        // serialized size could differ.
205        Err(Error::NotSupported)
206    }
207
208    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
209        Ok(self)
210    }
211
212    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
213        Ok(self)
214    }
215
216    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
217        // There is no obvious default way to implement a map.
218        Err(Error::NotSupported)
219    }
220
221    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
222        Ok(self)
223    }
224
225    fn serialize_struct_variant(
226        self,
227        _name: &'static str,
228        _variant_index: u32,
229        _variant: &'static str,
230        _len: usize,
231    ) -> Result<Self::SerializeStructVariant> {
232        // There is no obvious default implementation here.
233        Err(Error::NotSupported)
234    }
235
236    fn serialize_tuple_struct(
237        self,
238        _name: &'static str,
239        _len: usize,
240    ) -> Result<Self::SerializeTupleStruct> {
241        Ok(self)
242    }
243
244    fn serialize_tuple_variant(
245        self,
246        _name: &'static str,
247        _variant_index: u32,
248        _variant: &'static str,
249        _len: usize,
250    ) -> Result<Self::SerializeTupleVariant> {
251        Err(Error::NotSupported)
252    }
253}
254
255/// A sequence is serialized by prefixing each element with `true` and ending with `false`.
256impl<'a> ser::SerializeSeq for &'a mut Serializer {
257    // Must match the `Ok` type of the serializer.
258    type Ok = ();
259    // Must match the `Error` type of the serializer.
260    type Error = Error;
261
262    // Serialize a single element of the sequence.
263    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
264    where
265        T: ?Sized + Serialize,
266    {
267        true.serialize(&mut **self)?;
268        value.serialize(&mut **self)
269    }
270
271    // Close the sequence.
272    fn end(self) -> Result<()> {
273        false.serialize(self)
274    }
275}
276
277/// To serialize a tuple, simply output the elements since the size is known.
278impl<'a> ser::SerializeTuple for &'a mut Serializer {
279    type Ok = ();
280    type Error = Error;
281
282    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
283    where
284        T: ?Sized + Serialize,
285    {
286        value.serialize(&mut **self)
287    }
288
289    fn end(self) -> Result<()> {
290        Ok(())
291    }
292}
293
294/// Implement structs by serializing the contents in order.
295impl<'a> ser::SerializeStruct for &'a mut Serializer {
296    type Ok = ();
297    type Error = Error;
298
299    fn serialize_field<T>(&mut self, _key: &'static str, value: &T) -> Result<()>
300    where
301        T: ?Sized + Serialize,
302    {
303        value.serialize(&mut **self)
304    }
305
306    fn end(self) -> Result<()> {
307        Ok(())
308    }
309}
310
311/// To serialize a tuple struct, simply output the elements since the size is known.
312impl<'a> ser::SerializeTupleStruct for &'a mut Serializer {
313    type Ok = ();
314    type Error = Error;
315
316    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
317    where
318        T: ?Sized + Serialize,
319    {
320        value.serialize(&mut **self)
321    }
322
323    fn end(self) -> Result<()> {
324        Ok(())
325    }
326}
327
328#[cfg(test)]
329mod test {
330    use super::*;
331    use serde_derive::Serialize;
332
333    #[test]
334    fn test_simple_struct_ser() {
335        #[derive(Serialize)]
336        struct SimpleStruct {
337            a: u8,
338            b: u16,
339            c: u32,
340            d: bool
341        }
342        impl WritablePacket for SimpleStruct {
343            const PACKET_TYPE: u8 = 10;
344        }
345        let simple_struct = SimpleStruct { a: 1, b: 2, c: 3, d: true};
346        let mut buffer = Vec::new();
347        let output = &mut buffer;
348        output.write_packet(&simple_struct).unwrap();
349        assert_eq!(buffer, vec![
350            11, 0, // Length
351            10, // PACKET_TYPE
352            1, // a
353            2, 0, // b
354            3, 0, 0, 0, // c
355            1 // d
356        ]);
357    }
358
359    #[test]
360    fn test_vec_ser() {
361        #[derive(Serialize)]
362        struct VecStruct {
363            item: Vec<u8>
364        }
365        impl WritablePacket for VecStruct {
366            const PACKET_TYPE: u8 = 0xFF;
367        }
368        let vec_struct = VecStruct { item: vec![0, 1, 2, 3, 4] };
369        let mut buffer = Vec::new();
370        let output = &mut buffer;
371        output.write_packet(&vec_struct).unwrap();
372        assert_eq!(buffer, vec![
373            14, 0, // Length
374            0xFF, // Packet type
375            1, 0, // boolean, item
376            1, 1,
377            1, 2,
378            1, 3,
379            1, 4,
380            0 // False
381        ]);
382    }
383
384    mod option_tests {
385        use super::*;
386
387        #[derive(Serialize)]
388        struct OptionStruct {
389            mandatory: u8,
390            optional: Option<u8>
391        }
392        impl WritablePacket for OptionStruct {
393            const PACKET_TYPE: u8 = 3;
394        }
395
396        #[test]
397        fn test_some_ser() {
398            let some_struct = OptionStruct { mandatory: 10, optional: Some(10) };
399            let mut buffer = Vec::new();
400            let output = &mut buffer;
401            output.write_packet(&some_struct).unwrap();
402            assert_eq!(buffer, vec![
403                5, 0, // Length
404                3, // PACKET_TYPE
405                10, // mandatory
406                10 // optional
407            ]);
408        }
409
410        #[test]
411        fn test_none_ser() {
412            let some_struct = OptionStruct { mandatory: 10, optional: None };
413            let mut buffer = Vec::new();
414            let output = &mut buffer;
415            output.write_packet(&some_struct).unwrap();
416            assert_eq!(buffer, vec![
417                4, 0, // Length
418                3, // PACKET_TYPE
419                10 // mandatory
420            ]);
421        }
422    }
423}