ecksport_codec/
list.rs

1//! Shim trait to pass a list of a certain `RpcCodec`-able types.
2
3use crate::errors::CodecError;
4use crate::traits::RpcCodec;
5use crate::util;
6
7#[derive(Clone)]
8pub struct ListOf<T> {
9    list: Vec<T>,
10}
11
12impl<T> ListOf<T> {
13    pub fn new(list: Vec<T>) -> Self {
14        Self { list }
15    }
16
17    pub fn inner(&self) -> &[T] {
18        &self.list
19    }
20
21    pub fn inner_mut(&mut self) -> &mut [T] {
22        &mut self.list
23    }
24
25    pub fn into_inner(self) -> Vec<T> {
26        self.list
27    }
28
29    pub fn len(&self) -> usize {
30        self.list.len()
31    }
32
33    pub fn is_empty(&self) -> bool {
34        self.list.is_empty()
35    }
36}
37
38impl<T: RpcCodec> RpcCodec for ListOf<T> {
39    fn from_slice(buf: &[u8]) -> Result<Self, crate::CodecError> {
40        let mut cur = util::Cursor::new(buf);
41
42        let mut list = Vec::new();
43        let cnt = cur.take_u32()?;
44        for _ in 0..cnt {
45            let ent = cur.take_len_tagged_inst::<T>()?;
46            list.push(ent);
47        }
48
49        if !cur.is_at_end() {
50            return Err(CodecError::LeftoverBytes(
51                cur.remaining_bytes(),
52                cur.inner().len(),
53            ));
54        }
55
56        Ok(Self { list })
57    }
58
59    fn fill_buf(&self, buf: &mut Vec<u8>) -> Result<(), crate::CodecError> {
60        let cnt = self.list.len();
61        if cnt > u32::MAX as usize {
62            return Err(CodecError::ContainerTooLarge(cnt));
63        }
64
65        util::write_u32(cnt as u32, buf);
66        for e in &self.list {
67            util::write_len_tagged_inst(e, buf)?;
68        }
69
70        Ok(())
71    }
72}