ezcp/
subtask.rs

1use crate::error::Result;
2use crate::test::{Test, TestGenerator};
3use crate::Input;
4use std::rc::Rc;
5
6/// This struct represents a subtask.
7/// You can add tests, test generators and set a checker function.
8/// Once you are done, you can add the subtask to a task.
9pub struct Subtask {
10    pub(super) number: usize,
11    pub(super) tests: Vec<Test>,
12    pub(super) dependencies: Vec<usize>,
13    pub(super) checker: Option<Box<dyn Fn(Input) -> Result<()>>>,
14}
15
16impl Subtask {
17    /// This function creates a new subtask with `points`.
18    #[must_use]
19    pub fn new() -> Self {
20        Self {
21            number: 0,
22            tests: Vec::new(),
23            dependencies: Vec::new(),
24            checker: None,
25        }
26    }
27
28    /// This function adds a test generator to the subtask with the provided count.
29    /// Test generator is a function that returns a string.
30    pub fn add_test<F: Fn() -> String + 'static>(&mut self, number: i32, function: F) {
31        let test_generator = Rc::new(TestGenerator::new(function));
32
33        for _ in 0..(number as usize) {
34            self.tests.push(Test::new(test_generator.clone()));
35        }
36    }
37
38    /// This function adds a single test from a string.
39    pub fn add_test_str<S: Into<String>>(&mut self, input: S) {
40        let input: String = input.into();
41        let func = move || input.clone();
42        let test_generator = Rc::new(TestGenerator::new(func));
43        self.tests.push(Test::new(test_generator));
44    }
45
46    /// This function sets the checker function for the subtask.
47    /// The checker function receives the input and returns an error if the input is invalid.
48    /// If the input is valid, it should return `Ok(())`.
49    /// If the checker function is not set, the default checker will be used although it is not recommended.
50    pub fn set_checker<F: Fn(Input) -> Result<()> + 'static>(&mut self, function: F) {
51        self.checker = Some(Box::new(function));
52    }
53}