use core::ffi::c_int;
use myrmic_common::cells::{
CommandRequest, ERR_CELL_CMD_CELL_ERROR, ERR_CELL_CMD_CELL_NOT_PRESENT,
ERR_CELL_CMD_COMMAND_NOT_PRESENT, ERR_CELL_CMD_INTERNAL, ERR_CELL_CMD_SMALL_BUFFER,
ERR_CELL_CMD_TIMEOUT,
};
mod c_functions {
use core::ffi::c_int;
#[link(wasm_import_module = "cell")]
unsafe extern "C" {
pub(super) fn send_command(buffer: *const u8, length: c_int) -> c_int;
}
}
pub fn send_command(req: &CommandRequest) -> Result<(), CommandError> {
crate::host_functions::call(req, c_functions::send_command).map_err(Into::into)
}
#[derive(Copy, Clone)]
pub enum CommandError {
Timeout,
CellNotPresent,
ApiError,
CellError,
Internal,
SmallBuffer,
Other(i32),
}
impl CommandError {
pub fn describe(&self) -> &'static str {
match self {
CommandError::Timeout => "Command timed out",
CommandError::CellNotPresent => "Target cell not present",
CommandError::ApiError => "Command not present",
CommandError::CellError => "Cell error",
CommandError::Internal => "Internal error",
CommandError::SmallBuffer => "Buffer too small",
CommandError::Other(_) => "Other(_)",
}
}
}
impl From<c_int> for CommandError {
fn from(value: c_int) -> Self {
match value {
ERR_CELL_CMD_TIMEOUT => Self::Timeout,
ERR_CELL_CMD_CELL_NOT_PRESENT => Self::CellNotPresent,
ERR_CELL_CMD_COMMAND_NOT_PRESENT => Self::ApiError,
ERR_CELL_CMD_CELL_ERROR => Self::CellError,
ERR_CELL_CMD_INTERNAL => Self::Internal,
ERR_CELL_CMD_SMALL_BUFFER => Self::SmallBuffer,
n => Self::Other(n),
}
}
}
impl core::fmt::Display for CommandError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(self.describe())
}
}