simplelock 0.4.1

Simple abstractions for inter-process synchronization.
Documentation
use crate::*;

use std::{any::Any, panic};

/// Simple utility function for wrapping a closure with a lock.
///
/// This will handle panics safely as long as they are [`UnwindSafe`]. The
/// panic will be caught, the lock will be unlocked, and then the panic is
/// released. This assumes the operation provided is transactional and will
/// handle its own clean-up.
///
/// # Example
/// ```
/// # use simplelock::*;
/// # fn main() -> SimpleLockResult<()> {
/// let mut lock = default_lock("MyAppName")?;
/// let result = lock_until_finished(
///     &mut lock,
///     || {
///         // do something needing a lock.
/// #       42
///     }
/// );
/// #   assert_eq!(42, result.unwrap(), "Should have been Ok(()).");
/// #   Ok(())
/// # }
/// ```
///
/// [`UnwindSafe`]: https://doc.rust-lang.org/std/panic/trait.UnwindSafe.html
pub fn lock_until_finished<R: Any>(
    lock: &mut impl Lock,
    op: impl FnOnce() -> R + panic::UnwindSafe,
) -> SimpleLockResult<R> {
    // Based on the Lock configuration, this may either
    // fail with an error or hang until the lock is
    // acquired. Make sure your configuration and
    // error handling is set up in-sync.
    lock.lock()?;

    // We wrap our call with a panic catch. Note, this won't
    // catch ALL possible panics, just ones which are UnwindSafe.
    let result = panic::catch_unwind(op);

    // Based on the Lock configuration, this may either fail
    // with an error or fail silently and just return the
    // result. This matters because the Op is considered a
    // FnOnce, so if it is a transaction, the lock configs
    // inform the rollback requirements for the user.
    lock.unlock()?;

    // Unwrap the panic the op threw or re-wrap to fix
    // the type signature and return the real result.
    match result {
        Ok(x) => Ok(x),
        Err(e) => panic::resume_unwind(e),
    }
}

/// Get a lock with default configuration based on the feature enabled.
///
/// Two calls to this function, with the same argument, will provide unique objects but
/// will describe the same lock. For example, if the `file` feature is enabled, this will
/// return a unique [`FileLock`]. However, they will both point to the same file, and thus
/// lock operations on these objects will be in competition.
///
/// Note: If multiple features are enabled at once, we make no guarantees on the type of
/// lock returned. Internally though, we try to return the ones we have the strongest
/// guarantees around based on the OS. If you want consistency, either enable a single
/// feature or call the constructor needed directly.
///
/// # Examples
///
/// To enable `FileLock` by default, add this to your Cargo.toml:
/// ```toml
/// [dependencies]
/// simplelock = { version = "*", features = [ "file" ] }
/// ```
///
/// Then you can create a file lock in a general way like so:
///
/// ```rust
/// # use simplelock::*;
/// # fn main() -> SimpleLockResult<()> {
/// let mut lock = default_lock("MyAppName")?;
/// // Do something with the lock!
/// # Ok(())
/// # }
/// ```
pub fn default_lock(app_name: impl Into<String>) -> SimpleLockResult<Box<dyn Lock>> {
    LockBuilder::default().build(app_name)
}