1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//! Shim trait to pass a list of a certain `RpcCodec`-able types.

use crate::errors::CodecError;
use crate::traits::RpcCodec;
use crate::util;

#[derive(Clone)]
pub struct ListOf<T> {
    list: Vec<T>,
}

impl<T> ListOf<T> {
    pub fn new(list: Vec<T>) -> Self {
        Self { list }
    }

    pub fn inner(&self) -> &[T] {
        &self.list
    }

    pub fn inner_mut(&mut self) -> &mut [T] {
        &mut self.list
    }

    pub fn into_inner(self) -> Vec<T> {
        self.list
    }

    pub fn len(&self) -> usize {
        self.list.len()
    }

    pub fn is_empty(&self) -> bool {
        self.list.is_empty()
    }
}

impl<T: RpcCodec> RpcCodec for ListOf<T> {
    fn from_slice(buf: &[u8]) -> Result<Self, crate::CodecError> {
        let mut cur = util::Cursor::new(buf);

        let mut list = Vec::new();
        let cnt = cur.take_u32()?;
        for _ in 0..cnt {
            let ent = cur.take_len_tagged_inst::<T>()?;
            list.push(ent);
        }

        if !cur.is_at_end() {
            return Err(CodecError::LeftoverBytes(
                cur.remaining_bytes(),
                cur.inner().len(),
            ));
        }

        Ok(Self { list })
    }

    fn fill_buf(&self, buf: &mut Vec<u8>) -> Result<(), crate::CodecError> {
        let cnt = self.list.len();
        if cnt > u32::MAX as usize {
            return Err(CodecError::ContainerTooLarge(cnt));
        }

        util::write_u32(cnt as u32, buf);
        for e in &self.list {
            util::write_len_tagged_inst(e, buf)?;
        }

        Ok(())
    }
}