blackhole 0.20.2

...to throw your threads into.
Documentation
/*
==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--

Black Hole

Copyright (C) 2019-2020, 2022-2023  Anonymous

There are several releases over multiple years,
they are listed as ranges, such as: "2019-2020".

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.

::--::--::--::--::--::--::--::--::--::--::--::--::--::--::--::--
*/

//! # 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(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));
}