1
//! Utility functions for the rest of the crate.
2

            
3
use tor_persist::StateMgr;
4
use tracing::error;
5

            
6
/// A RAII guard that calls `<T as StateMgr>::unlock` on drop.
7
pub(crate) struct StateMgrUnlockGuard<'a, T: StateMgr + 'a> {
8
    /// The inner manager.
9
    mgr: &'a T,
10
}
11

            
12
impl<'a, T: StateMgr + 'a> Drop for StateMgrUnlockGuard<'a, T> {
13
    fn drop(&mut self) {
14
        if let Err(e) = self.mgr.unlock() {
15
            error!("Failed to unlock state manager: {}", e);
16
        }
17
    }
18
}
19

            
20
impl<'a, T: StateMgr + 'a> StateMgrUnlockGuard<'a, T> {
21
    /// Create an unlock guard.
22
    pub(crate) fn new(mgr: &'a T) -> Self {
23
        Self { mgr }
24
    }
25
    /// Consume the unlock guard without unlocking the state manager.
26
    pub(crate) fn disarm(self) {
27
        std::mem::forget(self);
28
    }
29
}