use std::cell::RefCell;
use std::io;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FileEvent {
BeforeAppend,
BeforeSync,
AfterSync,
}
type Callback = Box<dyn FnMut(FileEvent) -> io::Result<()>>;
thread_local! { static CALLBACK: RefCell<Option<Callback>> = RefCell::new(None); }
pub struct FileOperationScope;
impl FileOperationScope {
pub fn install(callback: impl FnMut(FileEvent) -> io::Result<()> + 'static) -> Self {
CALLBACK.with(|slot| *slot.borrow_mut() = Some(Box::new(callback)));
Self
}
}
impl Drop for FileOperationScope {
fn drop(&mut self) {
CALLBACK.with(|slot| *slot.borrow_mut() = None);
}
}
pub(super) fn event(event: FileEvent) -> io::Result<()> {
CALLBACK.with(|slot| match slot.borrow_mut().as_mut() {
Some(callback) => callback(event),
None => Ok(()),
})
}