use std::sync::Arc;
use std::sync::Mutex;
use base::error;
use crate::utils::FailHandle;
#[derive(Clone)]
pub struct RingBufferStopCallback {
_inner: Arc<Mutex<RingBufferStopCallbackInner>>,
}
impl RingBufferStopCallback {
pub fn new<C: 'static + FnMut() + Send>(cb: C) -> RingBufferStopCallback {
RingBufferStopCallback {
_inner: Arc::new(Mutex::new(RingBufferStopCallbackInner {
callback: Box::new(cb),
})),
}
}
}
struct RingBufferStopCallbackInner {
callback: Box<dyn FnMut() + Send>,
}
impl Drop for RingBufferStopCallbackInner {
fn drop(&mut self) {
(self.callback)();
}
}
pub fn fallible_closure<E: std::fmt::Display, C: FnMut() -> Result<(), E> + 'static + Send>(
fail_handle: Arc<dyn FailHandle>,
mut callback: C,
) -> impl FnMut() + 'static + Send {
move || match callback() {
Ok(()) => {}
Err(e) => {
error!("callback failed {}", e);
fail_handle.fail();
}
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use std::sync::Mutex;
use super::*;
fn task(_: RingBufferStopCallback) {}
#[test]
fn simple_raii_callback() {
let a = Arc::new(Mutex::new(0));
let ac = a.clone();
let cb = RingBufferStopCallback::new(move || {
*ac.lock().unwrap() = 1;
});
task(cb.clone());
task(cb.clone());
task(cb);
assert_eq!(*a.lock().unwrap(), 1);
}
}