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 std::fmt::Display;
7use crate::DominoError;
8use super::NUMBER_OF_CLASSES;
9
10/// Represents a complexity class as an integer value.
11///
12/// This struct enforces that the class value is within a valid range and provides
13/// conversion methods for display and numerical operations.
14#[derive(Debug, PartialEq, Eq, Clone, Copy)]
15pub struct ComplexityClass(pub usize);
16
17impl ComplexityClass {
18 /// Creates a new `ComplexityClass` instance if the provided value is within a valid range.
19 ///
20 /// # Arguments
21 ///
22 /// * `class` - The complexity class value.
23 ///
24 /// # Returns
25 ///
26 /// * `Ok(ComplexityClass)` - If the provided class is in the range `[1, NUMBER_OF_CLASSES]`.
27 /// * `Err(DominoError::InvalidClass)` - If the class is out of bounds.
28 ///
29 pub fn new(class: usize) -> Result<ComplexityClass, DominoError> {
30 if class == 0 || class > NUMBER_OF_CLASSES {
31 let err_msg = format!(
32 "The complexity class provided is not valid: {}.\nIt should be in the range [1, {}]",
33 class, NUMBER_OF_CLASSES
34 );
35 return Err(DominoError::InvalidClass(err_msg));
36 }
37
38 Ok(Self(class))
39 }
40}
41
42impl Display for ComplexityClass {
43 /// Formats the `ComplexityClass` as a string.
44 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45 f.write_str(format!("{}", self.0).as_str())
46 }
47}
48
49impl Into<f32> for ComplexityClass {
50 /// Converts the `ComplexityClass` into a floating-point number.
51 fn into(self) -> f32 {
52 self.0 as f32
53 }
54}