1extern crate alloc;
8
9use alloc::string::String;
10use core::fmt::{Display, Formatter};
11use core::str;
12
13use bytecheck::CheckBytes;
14use rkyv::{Archive, Deserialize, Serialize};
15
16#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize)]
25#[archive_attr(derive(CheckBytes))]
26pub enum ContractError {
27 Panic(String),
28 OutOfGas,
29 DoesNotExist,
30 Unknown,
31}
32
33impl ContractError {
34 #[cfg(feature = "abi")]
37 pub(crate) fn from_parts(code: i32, slice: &[u8]) -> Self {
38 fn get_msg(slice: &[u8]) -> String {
39 let msg_len = {
40 let mut msg_len_bytes = [0u8; 4];
41 msg_len_bytes.copy_from_slice(&slice[..4]);
42 u32::from_le_bytes(msg_len_bytes)
43 } as usize;
44
45 let msg = unsafe {
48 use alloc::string::ToString;
49 let msg_bytes = &slice[4..4 + msg_len];
50 let msg_str = str::from_utf8_unchecked(msg_bytes);
51 msg_str.to_string()
52 };
53
54 msg
55 }
56
57 match code {
58 -1 => Self::Panic(get_msg(slice)),
59 -2 => Self::OutOfGas,
60 -3 => Self::DoesNotExist,
61 i32::MIN => Self::Unknown,
62 _ => unreachable!("The host must guarantee that the code is valid"),
63 }
64 }
65
66 pub fn to_parts(&self, slice: &mut [u8]) -> i32 {
68 fn put_msg(msg: &str, slice: &mut [u8]) {
69 let msg_bytes = msg.as_bytes();
70 let msg_len = msg_bytes.len();
71
72 let mut msg_len_bytes = [0u8; 4];
73 msg_len_bytes.copy_from_slice(&(msg_len as u32).to_le_bytes());
74
75 slice[..4].copy_from_slice(&msg_len_bytes);
76 slice[4..4 + msg_len].copy_from_slice(msg_bytes);
77 }
78
79 match self {
80 Self::Panic(msg) => {
81 put_msg(msg, slice);
82 -1
83 }
84 Self::OutOfGas => -2,
85 Self::DoesNotExist => -3,
86 Self::Unknown => i32::MIN,
87 }
88 }
89}
90
91impl From<ContractError> for i32 {
92 fn from(err: ContractError) -> Self {
93 match err {
94 ContractError::Panic(_) => -1,
95 ContractError::OutOfGas => -2,
96 ContractError::DoesNotExist => -3,
97 ContractError::Unknown => i32::MIN,
98 }
99 }
100}
101
102impl Display for ContractError {
103 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
104 match self {
105 ContractError::Panic(msg) => write!(f, "Panic: {msg}"),
106 ContractError::OutOfGas => write!(f, "OutOfGas"),
107 ContractError::DoesNotExist => {
108 write!(f, "Contract does not exist")
109 }
110 ContractError::Unknown => write!(f, "Unknown"),
111 }
112 }
113}