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(())
}
}