namaste 0.19.0

Simple locks between processes
Documentation
// License: see LICENSE file at root directory of main branch

//! # Root

#![cfg(any(target_os = "linux", target_os = "l4re", target_os = "android", target_os = "windows"))]

use {
    core::time::Duration,
    std::{
        io::{Error, ErrorKind},
        thread,
        time::Instant,
    },
    crate::{Namaste, Result},
};

/// # Makes new `Namaste`
pub fn make<B>(id: B) -> Result<Namaste> where B: AsRef<[u8]> {
    Namaste::make(id)
}

/// # Tries to make a `Namaste`...
///
/// If *the same ID is in use*, waits and tries again until timed out.
pub fn make_wait<B>(id: B, timeout: Duration) -> Result<Namaste> where B: AsRef<[u8]> {
    const SLEEP_DURATION: Duration = Duration::from_millis(10);

    let start = Instant::now();
    loop {
        match make(&id) {
            Ok(namaste) => return Ok(namaste),
            Err(_) => {
                match Instant::now().checked_duration_since(start) {
                    Some(duration) => if duration > timeout {
                        return Err(Error::new(ErrorKind::TimedOut, __!("Timed out")));
                    },
                    None => return Err(Error::new(ErrorKind::Other, __!("Invalid system time"))),
                };
                thread::sleep(SLEEP_DURATION);
            },
        };
    }
}