// License: see LICENSE file at root directory of `master` branch

//! # Job

/// # A job to be used by [`BlackHole`][crate:BlackHole]
///
/// ## Usage
///
/// You can return new job from [`::run()`][::run()] for it to be run.
///
/// [crate:BlackHole]: struct.BlackHole.html
/// [::run()]: trait.Job.html#tymethod.run
pub trait Job: Send + 'static {

    /// # Runs the job
    fn run(&mut self) -> Option<Box<dyn Job>>;

}

/// # Runs a job to the end
pub fn run_to_end<J>(mut job: J) where J: Job {
    let mut job = job.run();
    while let Some(mut new_job) = job {
        job = new_job.run();
    }
}

/// # A job that runs once
///
/// ## Panics
///
/// It will panic if run more than once.
///
/// ## Examples
///
/// ```
/// use blackhole::{BlackHole, OneTime};
///
/// let black_hole = BlackHole::make(4, 8).unwrap();
/// for i in 0..10 {
///     match black_hole.throw(OneTime::new(move || println!("{}", i))) {
///         Ok(job) => if let Some(job) = job {
///             blackhole::run_to_end(job);
///         },
///         Err(err) => eprintln!("BlackHole... exploded: {}", err),
///     };
/// }
/// black_hole.escape_on_idle().unwrap();
/// ```
#[derive(Debug)]
pub struct OneTime<F> where F: FnOnce() + Send + 'static {

    /// # The job
    f: Option<F>,

}

impl<F> OneTime<F> where F: FnOnce() + Send + 'static {

    /// # Makes new instance
    pub fn new(f: F) -> Self {
        Self {
            f: Some(f),
        }
    }

}

impl<F> Job for OneTime<F> where F: FnOnce() + Send + 'static {

    fn run(&mut self) -> Option<Box<dyn Job>> {
        self.f.take().expect("OneTime job must be run at most once")();
        None
    }

}

#[test]
fn test_one_time() {
    use std::sync::{
        Arc,
        atomic::{self, AtomicBool},
    };

    const ORDERING: atomic::Ordering = atomic::Ordering::Relaxed;

    let data = Arc::new(AtomicBool::new(false));
    run_to_end({
        let data = data.clone();
        OneTime::new(move || data.store(true, ORDERING))
    });
    assert!(data.load(ORDERING));
}
