use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use crate::Result;
use crate::SnapshotError;
pub(crate) struct SnapshotGuard<'a> {
flag: &'a AtomicBool,
}
impl<'a> SnapshotGuard<'a> {
pub(crate) fn new(flag: &'a AtomicBool) -> Result<Self> {
let already_in_progress = flag
.compare_exchange(
false,
true,
Ordering::AcqRel, Ordering::Relaxed,
)
.map_err(|e| {
SnapshotError::OperationFailed(format!("SnapshotGuard::compare_exchange, {e:?}"))
})?;
if already_in_progress {
return Err(
SnapshotError::OperationFailed("Snapshot already in progress".to_string()).into(),
);
}
Ok(Self { flag })
}
}
impl Drop for SnapshotGuard<'_> {
fn drop(&mut self) {
self.flag.store(false, Ordering::SeqCst);
}
}