fj_core/validation/
validation_check.rs

1use std::fmt::Display;
2
3use crate::geometry::Geometry;
4
5use super::ValidationConfig;
6
7/// Run a specific validation check on an object
8///
9/// This trait is implemented once per validation check and object it applies
10/// to. `Self` is the object, while `T` identifies the validation check.
11pub trait ValidationCheck<T>: Sized {
12    /// Run the validation check on the implementing object
13    fn check(
14        object: &T,
15        geometry: &Geometry,
16        config: &ValidationConfig,
17    ) -> impl Iterator<Item = Self>;
18
19    /// Convenience method to run the check return the first error
20    ///
21    /// This method is designed for convenience over flexibility (it is intended
22    /// for use in unit tests), and thus always uses the default configuration.
23    fn check_and_return_first_error(
24        object: &T,
25        geometry: &Geometry,
26    ) -> Result<(), Self> {
27        let config = ValidationConfig::default();
28        let mut errors = Self::check(object, geometry, &config);
29
30        if let Some(err) = errors.next() {
31            return Err(err);
32        }
33
34        Ok(())
35    }
36
37    /// Convenience method to run the check and expect one error
38    ///
39    /// This method is designed for convenience over flexibility (it is intended
40    /// for use in unit tests), and thus always uses the default configuration.
41    fn check_and_expect_one_error(object: &T, geometry: &Geometry) -> Self
42    where
43        Self: Display,
44    {
45        let config = ValidationConfig::default();
46        let mut errors = Self::check(object, geometry, &config).peekable();
47
48        let err = errors
49            .next()
50            .expect("Expected one validation error; none found");
51
52        if errors.peek().is_some() {
53            println!("Unexpected validation errors:");
54
55            for err in errors {
56                println!("{err}");
57            }
58
59            panic!("Expected only one validation error")
60        }
61
62        err
63    }
64}