use core::ffi::c_int;
use crate::{ApiResult, RawBuf, error::ErrorCode};
mod c_functions {
use core::ffi::c_int;
#[link(wasm_import_module = "logging")]
unsafe extern "C" {
pub(super) fn log_host(buffer: *const u8, length: c_int, log_level: c_int) -> i32;
}
}
pub enum LogLevel {
Trace,
Debug,
Info,
Warn,
Error,
}
impl From<LogLevel> for i32 {
fn from(value: LogLevel) -> Self {
match value {
LogLevel::Trace => 0,
LogLevel::Debug => 1,
LogLevel::Info => 2,
LogLevel::Warn => 3,
LogLevel::Error => 4,
}
}
}
impl TryFrom<i32> for LogLevel {
type Error = ();
fn try_from(value: i32) -> Result<Self, <LogLevel as TryFrom<i32>>::Error> {
match value {
0 => Ok(LogLevel::Trace),
1 => Ok(LogLevel::Debug),
2 => Ok(LogLevel::Info),
3 => Ok(LogLevel::Warn),
4 => Ok(LogLevel::Error),
_ => Err(()),
}
}
}
pub fn log(msg: &str, log_level: LogLevel) -> ApiResult<()> {
unsafe { c_functions::log_host(msg.as_ptr(), msg.len() as c_int, log_level.into()) }.to_result()
}
pub fn log_buffer(buf: &RawBuf, log_level: LogLevel) -> ApiResult<()> {
unsafe { c_functions::log_host(buf.ptr, buf.len as i32, log_level.into()) }.to_result()
}
#[macro_export]
macro_rules! trace {
($($arg:tt)*) => {
$crate::log(&$crate::format!($($arg)*), $crate::LogLevel::Trace)
};
}
pub fn trace_str(msg: &str) -> ApiResult<()> {
log(msg, LogLevel::Trace)
}
#[macro_export]
macro_rules! debug {
($($arg:tt)*) => {
$crate::log(&$crate::format!($($arg)*), $crate::LogLevel::Debug)
};
}
pub fn debug_str(msg: &str) -> ApiResult<()> {
log(msg, LogLevel::Debug)
}
#[macro_export]
macro_rules! info {
($($arg:tt)*) => {
$crate::log(&$crate::format!($($arg)*), $crate::LogLevel::Info)
};
}
pub fn info_str(msg: &str) -> ApiResult<()> {
log(msg, LogLevel::Info)
}
#[macro_export]
macro_rules! warn {
($($arg:tt)*) => {
$crate::log(&$crate::format!($($arg)*), $crate::LogLevel::Warn)
};
}
pub fn warn_str(msg: &str) -> ApiResult<()> {
log(msg, LogLevel::Warn)
}
#[macro_export]
macro_rules! error {
($($arg:tt)*) => {
$crate::log(&$crate::format!($($arg)*), $crate::LogLevel::Error)
};
}
pub fn error_str(msg: &str) -> ApiResult<()> {
log(msg, LogLevel::Error)
}