1use std::{error::Error, fmt};
2
3#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
8pub struct LogicalPixels(f32);
9
10impl LogicalPixels {
11 pub fn new(value: f32) -> Result<Self, UnitError> {
13 positive_finite(value)
14 .then_some(Self(value))
15 .ok_or(UnitError::InvalidLogicalPixels { value })
16 }
17
18 pub const fn get(self) -> f32 {
20 self.0
21 }
22}
23
24#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
30pub struct WorldLength(f32);
31
32impl WorldLength {
33 pub fn new(value: f32) -> Result<Self, UnitError> {
35 positive_finite(value)
36 .then_some(Self(value))
37 .ok_or(UnitError::InvalidWorldLength { value })
38 }
39
40 pub const fn get(self) -> f32 {
42 self.0
43 }
44}
45
46#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
51pub struct PhysicalPerLogical(f32);
52
53impl PhysicalPerLogical {
54 pub fn new(value: f32) -> Result<Self, UnitError> {
56 positive_finite(value)
57 .then_some(Self(value))
58 .ok_or(UnitError::InvalidPhysicalPerLogical { value })
59 }
60
61 pub const fn get(self) -> f32 {
63 self.0
64 }
65}
66
67#[derive(Debug, Clone, Copy, PartialEq)]
69pub enum UnitError {
70 InvalidLogicalPixels {
72 value: f32,
74 },
75 InvalidWorldLength {
77 value: f32,
79 },
80 InvalidPhysicalPerLogical {
82 value: f32,
84 },
85}
86
87impl fmt::Display for UnitError {
88 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
89 match self {
90 Self::InvalidLogicalPixels { value } => {
91 write!(
92 formatter,
93 "logical pixel length must be positive and finite, got {value}"
94 )
95 }
96 Self::InvalidWorldLength { value } => {
97 write!(
98 formatter,
99 "world length must be positive and finite, got {value}"
100 )
101 }
102 Self::InvalidPhysicalPerLogical { value } => write!(
103 formatter,
104 "physical-per-logical ratio must be positive and finite, got {value}"
105 ),
106 }
107 }
108}
109
110impl Error for UnitError {}
111
112fn positive_finite(value: f32) -> bool {
113 value.is_finite() && value > 0.0
114}
115
116#[cfg(test)]
117mod tests {
118 use super::{LogicalPixels, PhysicalPerLogical, UnitError, WorldLength};
119
120 #[test]
121 fn scalar_units_reject_unlabelled_invalid_lengths() {
122 assert_eq!(LogicalPixels::new(2.0).unwrap().get(), 2.0);
123 assert_eq!(WorldLength::new(0.1).unwrap().get(), 0.1);
124 assert_eq!(PhysicalPerLogical::new(0.5).unwrap().get(), 0.5);
125 assert_eq!(
126 LogicalPixels::new(0.0),
127 Err(UnitError::InvalidLogicalPixels { value: 0.0 })
128 );
129 assert_eq!(
130 WorldLength::new(f32::INFINITY),
131 Err(UnitError::InvalidWorldLength {
132 value: f32::INFINITY,
133 })
134 );
135 assert_eq!(
136 PhysicalPerLogical::new(-1.0),
137 Err(UnitError::InvalidPhysicalPerLogical { value: -1.0 })
138 );
139 }
140}