use crate::{
engine::executor::{Cell, CellError, LiftFromCells, LiftFromCellsByValue, LowerToCells},
store::AsStoreId,
};
use core::cmp::max;
#[derive(Debug)]
pub struct InOutParams<'cells> {
cells: &'cells mut [Cell],
len_params: usize,
len_results: usize,
}
impl<'cells> InOutParams<'cells> {
pub fn new(
cells: &'cells mut [Cell],
len_params: usize,
len_results: usize,
) -> Result<Self, CellError> {
let required_cells = max(len_params, len_results);
if required_cells < cells.len() {
return Err(CellError::NotEnoughValues);
}
if required_cells > cells.len() {
return Err(CellError::NotEnoughCells);
}
Ok(Self {
cells,
len_params,
len_results,
})
}
pub fn params(&self) -> &[Cell] {
&self.cells[..self.len_params]
}
pub fn decode_params_into<T>(&self, store: impl AsStoreId, out: T) -> Result<(), CellError>
where
T: LiftFromCells<Value = ()>,
{
out.lift_from_cells(store, &mut self.params())
}
pub fn decode_params<T>(&self, store: impl AsStoreId) -> Result<T, CellError>
where
T: LiftFromCellsByValue,
{
<T as LiftFromCellsByValue>::lift_from_cells_by_value(store, &mut self.params())
}
pub fn encode_results<T>(
self,
store: impl AsStoreId,
results: T,
) -> Result<InOutResults<'cells>, CellError>
where
T: LowerToCells,
{
let mut cells = &mut self.cells[..self.len_results];
results.lower_to_cells(store, &mut cells)?;
Ok(InOutResults { cells })
}
}
#[derive(Debug)]
pub struct InOutResults<'cells> {
cells: &'cells mut [Cell],
}
impl<'cells> InOutResults<'cells> {
pub fn results(&self) -> &[Cell] {
self.cells
}
}