domino_lib/classify/
complexity_class.rs

1//! This module defines the `ComplexityClass` struct, which represents a class of computational complexity.
2//!
3//! The class is validated to ensure it falls within the defined range `[1, NUMBER_OF_CLASSES]`.
4//! It also implements `Display` for formatted output and `Into<f32>` for numeric conversion.
5
6use super::NUMBER_OF_CLASSES;
7use crate::DominoError;
8use std::cmp::Ordering;
9use std::fmt::Display;
10
11/// Represents a complexity class as an integer value.
12///
13/// This struct enforces that the class value is within a valid range and provides
14/// conversion methods for display and numerical operations.
15#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
16pub struct ComplexityClass(pub usize);
17
18impl ComplexityClass {
19    /// Creates a new `ComplexityClass` instance if the provided value is within a valid range.
20    ///
21    /// # Arguments
22    ///
23    /// * `class` - The complexity class value.
24    ///
25    /// # Returns
26    ///
27    /// * `Ok(ComplexityClass)` - If the provided class is in the range `[1, NUMBER_OF_CLASSES]`.
28    /// * `Err(DominoError::InvalidClass)` - If the class is out of bounds.
29    ///
30    pub fn new(class: usize) -> Result<ComplexityClass, DominoError> {
31        if class == 0 || class > NUMBER_OF_CLASSES {
32            let err_msg = format!(
33                "The complexity class provided is not valid: {}.\nIt should be in the range [1, {}]",
34                class, NUMBER_OF_CLASSES
35            );
36            return Err(DominoError::InvalidClass(err_msg));
37        }
38
39        Ok(Self(class))
40    }
41}
42
43impl Display for ComplexityClass {
44    /// Formats the `ComplexityClass` as a string.
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        write!(f, "{}", self.0)
47    }
48}
49
50impl Into<f32> for ComplexityClass {
51    /// Converts the `ComplexityClass` into a floating-point number.
52    fn into(self) -> f32 {
53        self.0 as f32
54    }
55}
56
57// Implement PartialEq to allow comparison with f32
58impl PartialEq<f32> for ComplexityClass {
59    fn eq(&self, other: &f32) -> bool {
60        (self.0 as f32) == *other
61    }
62}
63
64// Implement PartialOrd to allow ordering comparisons with f32
65impl PartialOrd<f32> for ComplexityClass {
66    fn partial_cmp(&self, other: &f32) -> Option<Ordering> {
67        (self.0 as f32).partial_cmp(other)
68    }
69}
70
71// Implement PartialEq to allow comparison with usize
72impl PartialEq<usize> for ComplexityClass {
73    fn eq(&self, other: &usize) -> bool {
74        self.0 == *other
75    }
76}
77
78// Implement PartialOrd to allow ordering comparisons with usize
79impl PartialOrd<usize> for ComplexityClass {
80    fn partial_cmp(&self, other: &usize) -> Option<Ordering> {
81        self.0.partial_cmp(other)
82    }
83}