use std::{error::Error, fmt};
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct LogicalPixels(f32);
impl LogicalPixels {
pub fn new(value: f32) -> Result<Self, UnitError> {
positive_finite(value)
.then_some(Self(value))
.ok_or(UnitError::InvalidLogicalPixels { value })
}
pub const fn get(self) -> f32 {
self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct WorldLength(f32);
impl WorldLength {
pub fn new(value: f32) -> Result<Self, UnitError> {
positive_finite(value)
.then_some(Self(value))
.ok_or(UnitError::InvalidWorldLength { value })
}
pub const fn get(self) -> f32 {
self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct PhysicalPerLogical(f32);
impl PhysicalPerLogical {
pub fn new(value: f32) -> Result<Self, UnitError> {
positive_finite(value)
.then_some(Self(value))
.ok_or(UnitError::InvalidPhysicalPerLogical { value })
}
pub const fn get(self) -> f32 {
self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum UnitError {
InvalidLogicalPixels {
value: f32,
},
InvalidWorldLength {
value: f32,
},
InvalidPhysicalPerLogical {
value: f32,
},
}
impl fmt::Display for UnitError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidLogicalPixels { value } => {
write!(
formatter,
"logical pixel length must be positive and finite, got {value}"
)
}
Self::InvalidWorldLength { value } => {
write!(
formatter,
"world length must be positive and finite, got {value}"
)
}
Self::InvalidPhysicalPerLogical { value } => write!(
formatter,
"physical-per-logical ratio must be positive and finite, got {value}"
),
}
}
}
impl Error for UnitError {}
fn positive_finite(value: f32) -> bool {
value.is_finite() && value > 0.0
}
#[cfg(test)]
mod tests {
use super::{LogicalPixels, PhysicalPerLogical, UnitError, WorldLength};
#[test]
fn scalar_units_reject_unlabelled_invalid_lengths() {
assert_eq!(LogicalPixels::new(2.0).unwrap().get(), 2.0);
assert_eq!(WorldLength::new(0.1).unwrap().get(), 0.1);
assert_eq!(PhysicalPerLogical::new(0.5).unwrap().get(), 0.5);
assert_eq!(
LogicalPixels::new(0.0),
Err(UnitError::InvalidLogicalPixels { value: 0.0 })
);
assert_eq!(
WorldLength::new(f32::INFINITY),
Err(UnitError::InvalidWorldLength {
value: f32::INFINITY,
})
);
assert_eq!(
PhysicalPerLogical::new(-1.0),
Err(UnitError::InvalidPhysicalPerLogical { value: -1.0 })
);
}
}