serde_rlp/
ser.rs

1// Copyright 2018 Althea Developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9use error::{Error, Result};
10use rlp;
11use serde::ser::{self, Serialize};
12use std::collections::VecDeque;
13use std::marker::Sized;
14
15pub struct Serializer {
16    // This is a vector of bytes that starts empty and bytes of RLP is appended as
17    // values are serialized.
18    output: Vec<u8>,
19    // When going deeper into the structure (i.e. when processing vector of vectors)
20    // this buffer is used to keep track of state "before" going deeper.
21    // This way we can save the state, and serialize nested sequence alone, and then
22    // once we're done with that sequence, we can go back to the saved state.
23    buffer: VecDeque<Vec<u8>>,
24}
25
26// By convention, the public API of a Serde deserializer is one or more `to_abc`
27// functions such as `to_string`, `to_bytes`, or `to_writer` depending on what
28// Rust types the serializer is able to produce as output.
29//
30// This basic serializer supports only `to_bytes`.
31pub fn to_bytes<T>(value: &T) -> Result<Vec<u8>>
32where
33    T: Serialize,
34{
35    let mut serializer = Serializer {
36        output: Vec::new(),
37        buffer: VecDeque::new(),
38    };
39    value.serialize(&mut serializer)?;
40    Ok(serializer.output)
41}
42
43impl<'a> ser::Serializer for &'a mut Serializer {
44    type Ok = ();
45    type Error = Error;
46
47    // Associated types for keeping track of additional state while serializing
48    // compound data structures like sequences and maps. In this case no
49    // additional state is required beyond what is already stored in the
50    // Serializer struct.
51    type SerializeSeq = Self;
52    type SerializeTuple = Self;
53    type SerializeTupleStruct = Self;
54    type SerializeTupleVariant = Self;
55    type SerializeMap = Self;
56    type SerializeStruct = Self;
57    type SerializeStructVariant = Self;
58
59    fn serialize_bool(self, _v: bool) -> Result<()> {
60        unimplemented!();
61    }
62
63    // JSON does not distinguish between different sizes of integers, so all
64    // signed integers will be serialized the same and all unsigned integers
65    // will be serialized the same. Other formats, especially compact binary
66    // formats, may need independent logic for the different sizes.
67    fn serialize_i8(self, v: i8) -> Result<()> {
68        self.serialize_i64(i64::from(v))
69    }
70
71    fn serialize_i16(self, v: i16) -> Result<()> {
72        self.serialize_i64(i64::from(v))
73    }
74
75    fn serialize_i32(self, v: i32) -> Result<()> {
76        self.serialize_i64(i64::from(v))
77    }
78
79    // Not particularly efficient but this is example code anyway. A more
80    // performant approach would be to use the `itoa` crate.
81    fn serialize_i64(self, _v: i64) -> Result<()> {
82        unimplemented!();
83    }
84
85    fn serialize_u8(self, v: u8) -> Result<()> {
86        self.serialize_bytes(&rlp::encode_number(v))
87    }
88
89    fn serialize_u16(self, v: u16) -> Result<()> {
90        self.serialize_bytes(&rlp::encode_number(v))
91    }
92
93    fn serialize_u32(self, v: u32) -> Result<()> {
94        self.serialize_bytes(&rlp::encode_number(v))
95    }
96
97    fn serialize_u64(self, v: u64) -> Result<()> {
98        self.serialize_bytes(&rlp::encode_number(v))
99    }
100
101    fn serialize_f32(self, _v: f32) -> Result<()> {
102        unimplemented!();
103    }
104
105    fn serialize_f64(self, _v: f64) -> Result<()> {
106        unimplemented!();
107    }
108
109    fn serialize_char(self, v: char) -> Result<()> {
110        self.serialize_str(&v.to_string())
111    }
112
113    fn serialize_str(self, v: &str) -> Result<()> {
114        if v.len() == 1 && v.as_bytes()[0] < 0x80 {
115            self.output.extend(v.as_bytes());
116        } else {
117            self.output.extend(rlp::encode_length(v.len() as u64, 0x80));
118            self.output.extend(v.as_bytes());
119        }
120        Ok(())
121    }
122
123    fn serialize_bytes(self, v: &[u8]) -> Result<()> {
124        // TODO: There is some duplication here that could be resolved later
125        if v.len() == 1 && v[0] < 0x80 {
126            self.output.extend(v);
127        } else {
128            self.output.extend(rlp::encode_length(v.len() as u64, 0x80));
129            self.output.extend(v);
130        }
131        Ok(())
132    }
133
134    // An absent optional is represented as the JSON `null`.
135    fn serialize_none(self) -> Result<()> {
136        unimplemented!();
137    }
138
139    fn serialize_some<T>(self, value: &T) -> Result<()>
140    where
141        T: ?Sized + Serialize,
142    {
143        // TODO: This probably can't be done better without introducing our own convention as described in RLP specification.
144        value.serialize(self)
145    }
146
147    fn serialize_unit(self) -> Result<()> {
148        // TODO: How to serialize unit types?
149        unimplemented!();
150    }
151
152    fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
153        unimplemented!();
154    }
155
156    fn serialize_unit_variant(
157        self,
158        _name: &'static str,
159        _variant_index: u32,
160        variant: &'static str,
161    ) -> Result<()> {
162        self.serialize_str(variant)
163    }
164
165    fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<()>
166    where
167        T: ?Sized + Serialize,
168    {
169        value.serialize(self)
170    }
171
172    fn serialize_newtype_variant<T>(
173        self,
174        _name: &'static str,
175        _variant_index: u32,
176        variant: &'static str,
177        value: &T,
178    ) -> Result<()>
179    where
180        T: ?Sized + Serialize,
181    {
182        variant.serialize(&mut *self)?;
183        value.serialize(&mut *self)?;
184        Ok(())
185    }
186
187    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
188        // Before going deeper we have to introduce state to our serializer.
189        // This way we can capture output from a processed sequence.
190        // Once thats done, we can pop current state at the end of the sequence.
191        // We don't really care about the passed length as length is mostly unused,
192        // as sequences are converted to bytes first, and then the length is
193        // length of actual bytes of data.
194        self.buffer.push_front(self.output.clone());
195        self.output.clear();
196        Ok(self)
197    }
198
199    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
200        // This works the same as normal sequence. Len is not used, but thats what
201        // trait needs.
202        self.serialize_seq(Some(len))
203    }
204
205    // Tuple structs look just like sequences in JSON.
206    fn serialize_tuple_struct(
207        self,
208        _name: &'static str,
209        len: usize,
210    ) -> Result<Self::SerializeTupleStruct> {
211        // Tuple structs works the same as normal tuple (and thus like a normal sequence)
212        self.serialize_seq(Some(len))
213    }
214
215    fn serialize_tuple_variant(
216        self,
217        _name: &'static str,
218        _variant_index: u32,
219        variant: &'static str,
220        _len: usize,
221    ) -> Result<Self::SerializeTupleVariant> {
222        variant.serialize(&mut *self)?;
223        Ok(self)
224    }
225
226    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
227        // Same as for sequences - we need to save current state of output,
228        // to be able to capture serialized values.
229        self.buffer.push_front(self.output.clone());
230        self.output.clear();
231        Ok(self)
232    }
233
234    fn serialize_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
235        self.serialize_map(Some(len))
236    }
237
238    fn serialize_struct_variant(
239        self,
240        _name: &'static str,
241        _variant_index: u32,
242        variant: &'static str,
243        _len: usize,
244    ) -> Result<Self::SerializeStructVariant> {
245        variant.serialize(&mut *self)?;
246        Ok(self)
247    }
248}
249
250impl<'a> ser::SerializeSeq for &'a mut Serializer {
251    type Ok = ();
252    type Error = Error;
253
254    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
255    where
256        T: ?Sized + Serialize,
257    {
258        // Serialize element of a sequence just fine
259        value.serialize(&mut **self)
260    }
261
262    fn end(self) -> Result<()> {
263        // Calculate the serialization of the sequence based on the captured output.
264        // Note that this output is cleared out before returning SerializeSeq instance,
265        // and saved on a deque.
266        let mut prefix = rlp::encode_length(self.output.len() as u64, 0xc0);
267        prefix.extend(self.output.clone());
268        // This will get the current output, and after that pop the top of the buffer,
269        // which is the output *before* serializing the sequence.
270        self.output = self.buffer.pop_front().unwrap(); // This unwrap is safe assuming the normal path of the code.
271        self.output.extend(prefix);
272        Ok(())
273    }
274}
275
276// Same thing but for tuples.
277impl<'a> ser::SerializeTuple for &'a mut Serializer {
278    type Ok = ();
279    type Error = Error;
280
281    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
282    where
283        T: ?Sized + Serialize,
284    {
285        value.serialize(&mut **self)
286    }
287
288    fn end(self) -> Result<()> {
289        let mut prefix = rlp::encode_length(self.output.len() as u64, 0xc0);
290        prefix.extend(self.output.clone());
291        // Restore original state after capturing this sequence
292        self.output = self.buffer.pop_front().unwrap();
293        self.output.extend(prefix);
294        Ok(())
295    }
296}
297
298// Same thing but for tuple structs.
299impl<'a> ser::SerializeTupleStruct for &'a mut Serializer {
300    type Ok = ();
301    type Error = Error;
302
303    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
304    where
305        T: ?Sized + Serialize,
306    {
307        value.serialize(&mut **self)
308    }
309
310    fn end(self) -> Result<()> {
311        Ok(())
312    }
313}
314
315impl<'a> ser::SerializeTupleVariant for &'a mut Serializer {
316    type Ok = ();
317    type Error = Error;
318
319    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
320    where
321        T: ?Sized + Serialize,
322    {
323        value.serialize(&mut **self)
324    }
325
326    fn end(self) -> Result<()> {
327        Ok(())
328    }
329}
330
331impl<'a> ser::SerializeMap for &'a mut Serializer {
332    type Ok = ();
333    type Error = Error;
334
335    fn serialize_key<T>(&mut self, key: &T) -> Result<()>
336    where
337        T: ?Sized + Serialize,
338    {
339        key.serialize(&mut **self)
340    }
341
342    fn serialize_value<T>(&mut self, value: &T) -> Result<()>
343    where
344        T: ?Sized + Serialize,
345    {
346        value.serialize(&mut **self)
347    }
348
349    fn end(self) -> Result<()> {
350        Ok(())
351    }
352}
353
354impl<'a> ser::SerializeStruct for &'a mut Serializer {
355    type Ok = ();
356    type Error = Error;
357
358    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
359    where
360        T: ?Sized + Serialize,
361    {
362        // Serialize element of a structure as a sequence [key, value].
363        let dummy_seq = (&key, &value);
364        dummy_seq.serialize(&mut **self)
365    }
366
367    fn end(self) -> Result<()> {
368        let mut prefix = rlp::encode_length(self.output.len() as u64, 0xc0);
369        prefix.extend(self.output.clone());
370        self.output = self.buffer.pop_front().unwrap(); // This unwrap is safe assuming the normal path of the code.
371        self.output.extend(prefix);
372        Ok(())
373    }
374}
375
376impl<'a> ser::SerializeStructVariant for &'a mut Serializer {
377    type Ok = ();
378    type Error = Error;
379
380    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
381    where
382        T: ?Sized + Serialize,
383    {
384        key.serialize(&mut **self)?;
385        value.serialize(&mut **self)
386    }
387
388    fn end(self) -> Result<()> {
389        Ok(())
390    }
391}
392
393#[test]
394fn test_emptystring() {
395    assert_eq!(to_bytes(&"".to_string()).unwrap(), [0x80]);
396}
397
398#[test]
399fn test_shortstring() {
400    assert_eq!(
401        to_bytes(&"dog".to_string()).unwrap(),
402        [0x83, 0x64, 0x6f, 0x67]
403    );
404}
405
406#[test]
407fn test_shortlist() {
408    assert_eq!(
409        to_bytes(&vec!["cat", "dog"]).unwrap(),
410        [0xc8, 0x83, 0x63, 0x61, 0x74, 0x83, 0x64, 0x6f, 0x67]
411    );
412}
413
414#[test]
415fn test_shortlist_as_tuple() {
416    let data = ("cat", "dog");
417    assert_eq!(
418        to_bytes(&data).unwrap(),
419        [0xc8, 0x83, 0x63, 0x61, 0x74, 0x83, 0x64, 0x6f, 0x67]
420    );
421}
422
423#[test]
424fn test_wrapped_shortlist() {
425    assert_eq!(
426        to_bytes(&vec![vec!["cat", "dog"]]).unwrap(),
427        [0xc9, 0xc8, 0x83, 0x63, 0x61, 0x74, 0x83, 0x64, 0x6f, 0x67]
428    );
429}
430
431#[test]
432fn test_nested_shortlist() {
433    assert_eq!(
434        to_bytes(&vec![vec!["cat", "dog"], vec!["cat", "dog"]]).unwrap(),
435        [
436            0xd2, 0xc8, 0x83, 0x63, 0x61, 0x74, 0x83, 0x64, 0x6f, 0x67, 0xc8, 0x83, 0x63, 0x61,
437            0x74, 0x83, 0x64, 0x6f, 0x67,
438        ]
439    );
440}
441
442#[test]
443fn test_long_string() {
444    assert_eq!(
445        to_bytes(&"Lorem ipsum dolor sit amet, consectetur adipisicing elit".to_string()).unwrap(),
446        vec![
447            0xb8, 0x38, 0x4c, 0x6f, 0x72, 0x65, 0x6d, 0x20, 0x69, 0x70, 0x73, 0x75, 0x6d, 0x20,
448            0x64, 0x6f, 0x6c, 0x6f, 0x72, 0x20, 0x73, 0x69, 0x74, 0x20, 0x61, 0x6d, 0x65, 0x74,
449            0x2c, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x65, 0x63, 0x74, 0x65, 0x74, 0x75, 0x72, 0x20,
450            0x61, 0x64, 0x69, 0x70, 0x69, 0x73, 0x69, 0x63, 0x69, 0x6e, 0x67, 0x20, 0x65, 0x6c,
451            0x69, 0x74,
452        ]
453    );
454}
455
456#[test]
457fn test_integer_0() {
458    assert_eq!(to_bytes(&0u8).unwrap(), vec![0x00]);
459}
460
461#[test]
462fn test_integer_15() {
463    assert_eq!(to_bytes(&15u8).unwrap(), vec![0x0f]);
464}
465
466#[test]
467fn test_integer_1024() {
468    assert_eq!(to_bytes(&1024u16).unwrap(), vec![0x82, 0x04, 0x00]);
469}
470
471#[test]
472fn test_integer_1024_u32() {
473    assert_eq!(to_bytes(&1024u32).unwrap(), vec![0x82, 0x04, 0x00]);
474}
475
476#[test]
477fn test_array() {
478    // "The set theoretical representation of three"
479    let data = vec![vec![], vec![vec![]], vec![vec![], vec![Vec::<u8>::new()]]];
480    assert_eq!(
481        to_bytes(&data).unwrap(),
482        [0xc7, 0xc0, 0xc1, 0xc0, 0xc3, 0xc0, 0xc1, 0xc0]
483    );
484}
485
486#[test]
487fn test_kv() {
488    let data = vec![vec!["key1", "value1"], vec!["key2", "value2"]];
489    assert_eq!(
490        to_bytes(&data).unwrap(),
491        [
492            0xda, 0xcc, 0x84, 0x6b, 0x65, 0x79, 0x31, 0x86, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x31,
493            0xcc, 0x84, 0x6b, 0x65, 0x79, 0x32, 0x86, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x32
494        ]
495    );
496}