use crate::call::Selector;
use ink_prelude::{
vec,
vec::Vec,
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CallData {
bytes: Vec<u8>,
}
impl CallData {
pub fn new(selector: Selector) -> Self {
let bytes = selector.to_bytes();
Self {
bytes: vec![bytes[0], bytes[1], bytes[2], bytes[3]],
}
}
pub fn push_arg<A>(&mut self, arg: &A)
where
A: scale::Encode,
{
arg.encode_to(&mut self.bytes)
}
pub fn selector(&self) -> Selector {
debug_assert!(self.bytes.len() >= 4);
let bytes = [self.bytes[0], self.bytes[1], self.bytes[2], self.bytes[3]];
bytes.into()
}
pub fn params(&self) -> &[u8] {
debug_assert!(self.bytes.len() >= 4);
&self.bytes[4..]
}
pub fn to_bytes(&self) -> &[u8] {
&self.bytes
}
}
impl scale::Encode for CallData {
fn size_hint(&self) -> usize {
self.bytes.len()
}
fn encode_to<T: scale::Output + ?Sized>(&self, dest: &mut T) {
dest.write(self.bytes.as_slice());
}
}
impl scale::Decode for CallData {
fn decode<I: scale::Input>(
input: &mut I,
) -> core::result::Result<Self, scale::Error> {
let remaining_len = input.remaining_len().unwrap_or(None).unwrap_or(0);
let mut bytes = Vec::with_capacity(remaining_len);
while let Ok(byte) = input.read_byte() {
bytes.push(byte);
}
if bytes.len() < 4 {
return Err(scale::Error::from(
"require at least 4 bytes for input data",
))
}
Ok(Self { bytes })
}
}