Skip to content

Commit

Permalink
Allow clients to set a log callback.
Browse files Browse the repository at this point in the history
This depends on mozilla/cubeb#802.
  • Loading branch information
mutexlox-signal committed Oct 15, 2024
1 parent d9be0bf commit 451b9d6
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
31 changes: 30 additions & 1 deletion cubeb-core/src/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
// This program is made available under an ISC-style license. See the
// accompanying file LICENSE for details.

use ffi;
use std::ffi::{c_char, CStr};
use std::sync::Mutex;
use {ffi, Error, Result};

/// Level (verbosity) of logging for a particular cubeb context.
#[derive(PartialEq, Eq, Clone, Debug, Copy, PartialOrd, Ord)]
Expand Down Expand Up @@ -31,6 +33,33 @@ pub fn log_enabled() -> bool {
unsafe { ffi::cubeb_log_get_level() != LogLevel::Disabled as _ }
}

static LOG_CALLBACK: Mutex<Option<fn(s: &CStr)>> = Mutex::new(None);

unsafe extern "C" fn log_callback_wrapper(s: *const c_char) {
if let Ok(guard) = LOG_CALLBACK.lock() {
if let Some(f) = *guard {
f(CStr::from_ptr(s));
}
// Do nothing if there is no callback.
}
// Silently fail if lock cannot be acquired.
}

pub fn set_logging(level: LogLevel, f: Option<fn(s: &CStr)>) -> Result<()> {
match LOG_CALLBACK.lock() {
Ok(mut guard) => {
*guard = f;
}
Err(_) => return Err(Error::error()),
}
unsafe {
call!(ffi::cubeb_set_log_callback_string(
level as u32,
Some(log_callback_wrapper)
))
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
6 changes: 6 additions & 0 deletions cubeb-sys/src/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,19 @@ cubeb_enum! {
}

pub type cubeb_log_callback = Option<unsafe extern "C" fn(*const c_char, ...)>;
pub type cubeb_log_callback_string = Option<unsafe extern "C" fn(*const c_char)>;

extern "C" {
pub fn cubeb_set_log_callback(
log_level: cubeb_log_level,
log_callback: cubeb_log_callback,
) -> c_int;

pub fn cubeb_set_log_callback_string(
log_level: cubeb_log_level,
log_callback: cubeb_log_callback_string,
) -> c_int;

pub fn cubeb_log_get_callback() -> cubeb_log_callback;
pub fn cubeb_log_get_level() -> cubeb_log_level;

Expand Down

0 comments on commit 451b9d6

Please sign in to comment.