whasm/grammar/core/
list.rs

1use super::*;
2
3/// A `List<T>` is a wrapper for a `Vec<T>`. It differs from a `Vec<T>` on how it is deserialized.
4/// The serialization of a `Vec<T>` begins with the number of elements `N` in the vector followed by
5/// each of the `N` elements.
6/// The serialization of a `List<T>` starts with the first element and continues reading until the
7/// iterator is exhausted.
8/// 
9/// After deserializing the last element of `List<T>`, the iterator must be exhausted. If not, the
10/// `List<T>` will try to deserialize a new `T` and append it to the list.
11/// 
12/// # Example
13/// 
14/// ```
15/// # use whasm::grammar::*;
16/// let mut iter = [0x01, 0x02, 0x03, 0x04].iter().copied();
17/// let List(result): List<Byte> = deserialize(&mut iter).unwrap();
18/// assert_eq!(result, vec![0x01, 0x02, 0x03, 0x04]);
19/// assert_eq!(iter.next(), None);
20/// ```
21/// 
22/// Deserialization will return an error if the iterator is not exhausted.
23/// 
24/// ```
25/// # use whasm::grammar::*;
26/// let mut iter = [0x00, 0x00, 0x00, 0x00, 0x05, 0x06].iter().copied();
27/// let result: Result<List<f32>> = deserialize(&mut iter);
28/// assert!(result.is_err());
29/// ```
30#[derive(Debug, PartialEq)]
31pub struct List<T: Grammar>(pub Vec<T>);
32
33impl<T: Grammar> Grammar for List<T> {
34    fn deserialize<Iter: Iterator<Item=u8>>(iter: &mut Iter) -> Result<Self> {
35        Ok(List({
36            let mut result = vec![];
37            let mut iter = iter.peekable();
38            while let Some(_) = iter.peek() {
39                result.push(deserialize(&mut iter)?);
40            }
41            result
42        }))
43    }
44}
45
46#[cfg(test)]
47mod test {
48    use crate as whasm;
49    use whasm::grammar::*;
50
51    #[test]
52    fn can_deserialize_list() {
53        let mut iter = [0x2A, 0xAA, 0x00, 0xAA, 0x80, 0x00].iter().copied();
54        let List(result): List<u8> = deserialize(&mut iter).unwrap();
55        assert_eq!(result, [42, 42, 42]);
56    }
57}