use nutype::nutype;
use std::fmt::Formatter;
#[nutype(
const_fn,
sanitize(with = clamp_finite_0_to_1),
derive(Default, Debug, Deref, Clone, Copy, PartialEq, PartialOrd),
default = 0.0,
)]
pub struct Progress(f32);
const fn clamp_finite_0_to_1(val: f32) -> f32 {
if val.is_finite() {
val.clamp(0.0, 1.0)
} else {
val
}
}
impl Progress {
pub const ZERO: Self = Self::new(0.0);
pub const DONE: Self = Self::new(1.0);
pub fn finished(self) -> bool {
let value = *self;
value.is_finite() && value >= 1.0 - f32::EPSILON
}
pub fn is_finite(self) -> bool {
(*self).is_finite()
}
}
impl std::fmt::Display for Progress {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(&(**self * 100.0), f)?;
f.write_str("%")
}
}
impl From<bool> for Progress {
fn from(val: bool) -> Self {
Self::new(if val { 1.0 } else { 0.0 })
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_progress_creation() {
let progress = Progress::new(0.5);
assert_eq!(*progress, 0.5);
let zero = Progress::ZERO;
assert_eq!(*zero, 0.0);
let done = Progress::DONE;
assert_eq!(*done, 1.0);
}
#[test]
fn test_progress_clamping() {
let over = Progress::new(1.5);
assert_eq!(*over, 1.0);
let under = Progress::new(-0.5);
assert_eq!(*under, 0.0);
let normal = Progress::new(0.75);
assert_eq!(*normal, 0.75);
}
#[test]
fn test_progress_finished() {
assert!(Progress::DONE.finished());
assert!(Progress::new(1.0).finished());
assert!(!Progress::new(0.99).finished());
assert!(!Progress::ZERO.finished());
let almost_done = Progress::new(1.0 - f32::EPSILON / 2.0);
assert!(almost_done.finished());
assert!(!Progress::new(f32::NAN).finished());
assert!(!Progress::new(f32::INFINITY).finished());
}
#[test]
fn test_progress_from_bool() {
let from_true: Progress = true.into();
assert_eq!(from_true, Progress::DONE);
let from_false: Progress = false.into();
assert_eq!(from_false, Progress::ZERO);
}
#[test]
fn test_progress_comparison() {
let low = Progress::new(0.3);
let high = Progress::new(0.7);
assert!(low < high);
assert!(high > low);
assert_eq!(low, Progress::new(0.3));
assert_ne!(low, high);
}
#[test]
fn test_progress_default() {
let default_progress = Progress::default();
assert_eq!(default_progress, Progress::ZERO);
}
#[test]
fn test_progress_non_finite_values() {
let nan_progress = Progress::new(f32::NAN);
assert!(!nan_progress.is_finite());
assert!((*nan_progress).is_nan());
let inf_progress = Progress::new(f32::INFINITY);
assert!(!inf_progress.is_finite());
assert!((*inf_progress).is_infinite());
let neg_inf_progress = Progress::new(f32::NEG_INFINITY);
assert!(!neg_inf_progress.is_finite());
assert!((*neg_inf_progress).is_infinite());
}
#[test]
fn test_progress_constants() {
assert_eq!(*Progress::ZERO, 0.0);
assert_eq!(*Progress::DONE, 1.0);
assert!(Progress::DONE.is_finite());
assert!(Progress::ZERO.is_finite());
let nan_progress = Progress::new(f32::NAN);
let inf_progress = Progress::new(f32::INFINITY);
assert!(!nan_progress.is_finite());
assert!(!inf_progress.is_finite());
}
}