#![no_std]
#![cfg_attr(docsrs, feature(doc_cfg))]
mod flags;
pub use flags::*;
mod host;
mod macros;
pub use host::{HostFn, HostFnImpl};
pub const fn u256_bytes(value: u64) -> [u8; 32] {
let mut buffer = [0u8; 32];
let bytes = value.to_le_bytes();
buffer[0] = bytes[0];
buffer[1] = bytes[1];
buffer[2] = bytes[2];
buffer[3] = bytes[3];
buffer[4] = bytes[4];
buffer[5] = bytes[5];
buffer[6] = bytes[6];
buffer[7] = bytes[7];
buffer
}
macro_rules! define_error_codes {
(
$(
$( #[$attr:meta] )*
$name:ident = $discr:literal,
)*
) => {
#[derive(Debug, PartialEq, Eq)]
#[repr(u32)]
pub enum ReturnErrorCode {
Success = 0,
$(
$( #[$attr] )*
$name = $discr,
)*
Unknown,
}
impl From<ReturnCode> for Result {
fn from(return_code: ReturnCode) -> Self {
match return_code.0 {
0 => Ok(()),
$(
$discr => Err(ReturnErrorCode::$name),
)*
_ => Err(ReturnErrorCode::Unknown),
}
}
}
};
}
impl From<ReturnErrorCode> for u32 {
fn from(code: ReturnErrorCode) -> u32 {
code as u32
}
}
impl From<ReturnErrorCode> for u64 {
fn from(error: ReturnErrorCode) -> Self {
u32::from(error).into()
}
}
define_error_codes! {
CalleeTrapped = 1,
CalleeReverted = 2,
KeyNotFound = 3,
TransferFailed = 4,
OutOfResources = 5,
EcdsaRecoveryFailed = 7,
Sr25519VerifyFailed = 8,
DuplicateContractAddress = 11,
}
#[repr(transparent)]
pub struct ReturnCode(u32);
const SENTINEL: u32 = u32::MAX;
impl From<ReturnCode> for Option<u32> {
fn from(code: ReturnCode) -> Self {
(code.0 < SENTINEL).then_some(code.0)
}
}
impl ReturnCode {
pub fn into_u32(self) -> u32 {
self.0
}
pub fn into_bool(self) -> bool {
self.0.ne(&0)
}
}
type Result = core::result::Result<(), ReturnErrorCode>;
pub fn pack_hi_lo(hi: u32, lo: u32) -> u64 {
((hi as u64) << 32) | lo as u64
}