Skip to content

Commit

Permalink
cleanup: avoid allocation for log levels that aren't enabled (#67)
Browse files Browse the repository at this point in the history
  • Loading branch information
zshipko authored Oct 22, 2024
1 parent 77041c3 commit b33b7ad
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 5 deletions.
1 change: 1 addition & 0 deletions src/extism.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ extern "C" {
pub fn log_warn(offs: u64);
pub fn log_error(offs: u64);
pub fn log_trace(offs: u64);
pub fn get_log_level() -> i32;
}

/// Loads a byte array from Extism's memory. Only use this if you
Expand Down
16 changes: 14 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,23 @@ pub type SharedFnResult<T> = Result<T, Error>;
/// Logging levels
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogLevel {
Info,
Trace,
Debug,
Info,
Warn,
Error,
Trace,
}

impl LogLevel {
pub const fn to_int(self) -> i32 {
match self {
LogLevel::Trace => 0,
LogLevel::Debug => 1,
LogLevel::Info => 2,
LogLevel::Warn => 3,
LogLevel::Error => 4,
}
}
}

/// Re-export of `serde_json`
Expand Down
9 changes: 6 additions & 3 deletions src/macros.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
#[macro_export]
macro_rules! log {
($lvl:expr, $($arg:tt)+) => {{
let fmt = format!($($arg)+);
let memory = $crate::Memory::from_bytes(&fmt).unwrap();
memory.log($lvl)
let level = unsafe { $crate::extism::get_log_level() };
if $lvl.to_int() >= level && level != i32::MAX {
let fmt = format!($($arg)+);
let memory = $crate::Memory::from_bytes(&fmt).unwrap();
memory.log($lvl)
}
}}
}

Expand Down

0 comments on commit b33b7ad

Please sign in to comment.