simulcrypt 0.1.1

DVB SimulCrypt (ETSI TS 103 197) head-end protocol: ECMG client, EMMG server, control words
Documentation
//! `std::sync::Mutex` helper shared by the registries of the crate.

use std::sync::{
    Mutex,
    MutexGuard,
};

/// Even if someone panicked under this lock, the protected state (usually just a
/// `HashMap`/`HashSet` of CAS channels or streams) is almost certainly still logically valid -
/// there is no point in locking it away forever. The guard is recovered, but the poisoning is
/// logged loudly: it is always the result of a bug that would otherwise go unnoticed.
pub trait MutexExt<T> {
    /// `lock()` that does not panic on a poisoned mutex - logs and returns the guard as usual.
    fn lock_or_recover(&self) -> MutexGuard<'_, T>;
}

impl<T> MutexExt<T> for Mutex<T> {
    fn lock_or_recover(&self) -> MutexGuard<'_, T> {
        self.lock().unwrap_or_else(|poisoned| {
            tracing::error!(
                "recovering from a poisoned mutex - a prior panic may have left shared state \
                 inconsistent, this is always a bug"
            );
            poisoned.into_inner()
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn lock_or_recover_survives_a_prior_panic_instead_of_panicking_forever() {
        let mutex = Mutex::new(0);

        let panicked = std::panic::catch_unwind(|| {
            let mut guard = mutex.lock().unwrap();
            *guard = 1;
            panic!("simulated bug while holding the lock");
        });
        assert!(panicked.is_err());
        assert!(
            mutex.is_poisoned(),
            "the mutex must actually be poisoned by now"
        );

        // Plain `.lock().unwrap()` would panic here too - `lock_or_recover` must not.
        let guard = mutex.lock_or_recover();
        assert_eq!(
            *guard, 1,
            "the write made before the panic must still be visible"
        );
    }
}