1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// 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<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::{ActiveLimit, Blackhole, OneTime};
///
/// let blackhole = Blackhole::make(ActiveLimit::new(4), 8).unwrap();
/// for i in 0..10 {
///     match blackhole.throw(OneTime::new(move || println!("{}", i))) {
///         Ok(job) => if let Some(job) = job {
///             blackhole::run_to_end(job);
///         },
///         Err(err) => eprintln!("Blackhole is... exploded: {}", err),
///     };
/// }
/// blackhole.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<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, ATOMIC_BOOL_INIT},
    };

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

    let data = Arc::new(ATOMIC_BOOL_INIT);
    assert!(data.load(ORDERING) == false);

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