blob: 838c29a3aabd17b88ddf931c999db482b779a9aa (
plain) (
blame)
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
|
use crate::{ProgramCollect, program::Program};
/// Trait for defining initialization/setup logic for a `Program`.
///
/// Implementors can define custom setup behavior that will be executed
/// when the program is initialized via [`Program::with_setup`].
///
/// # Type Parameters
///
/// * `C` - The program collect type, which must implement [`ProgramCollect`]
/// and have `Enum = C` (i.e., it collects itself).
pub trait ProgramSetup<C>
where
C: ProgramCollect<Enum = C>,
{
/// Perform setup on the given program.
///
/// This method consumes the setup instance (`self`) and is called once
/// during program initialization.
///
/// # Arguments
///
/// * `program` - A mutable reference to the [`Program`] being set up.
fn setup(self, program: &mut Program<C>);
}
impl<C> Program<C>
where
C: ProgramCollect<Enum = C>,
{
/// Load and execute init logic
pub fn with_setup<S: ProgramSetup<C> + 'static>(&mut self, setup: S) {
S::setup(setup, self);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::MockProgramCollect;
struct TestSetup {
called: std::rc::Rc<std::cell::Cell<bool>>,
}
impl ProgramSetup<MockProgramCollect> for TestSetup {
fn setup(self, _program: &mut Program<MockProgramCollect>) {
self.called.set(true);
}
}
#[test]
fn test_with_setup_calls_setup() {
let called = std::rc::Rc::new(std::cell::Cell::new(false));
let setup = TestSetup {
called: std::rc::Rc::clone(&called),
};
let mut program: Program<MockProgramCollect> = Program::new_with_args(["test"]);
program.with_setup(setup);
assert!(called.get());
}
}
|