1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
use std::{
    cmp::Ordering,
    ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign},
};

use thiserror::Error;

pub type Unit = i32;

#[derive(Error, Debug, PartialEq, Eq)]
pub enum QuantityValueError {
    #[error("got NaN")]
    NaN,
}

/// A quantity with associated units.
///
/// The units are either base SI units and several extensions (for example m,
/// s, px) or derived units (for example rad, m/s⁻²). Only unit powers up to
/// +/-7 are supported: id est m² or m⁻² are supported but m⁸ is not.
#[derive(Debug, Clone, Copy)]
pub struct Quantity<const U: Unit>(pub(crate) f32);

impl<const U: Unit> Quantity<U> {
    pub const ZERO: Self = Quantity(0.);
    pub const ONE: Self = Quantity(1.);

    /// Creates a new quantity without checking the value.
    ///
    /// It is expected that the value is not a NaN. If NaN is given, the type
    /// might behave strangely or panic during some of the operations.
    pub const fn new_unchecked(value: f32) -> Self {
        Self(value)
    }

    /// Crates a new quantity.
    ///
    /// # Panics
    ///
    /// Panics if `value` is NaN.
    pub fn new(value: f32) -> Self {
        panic_on_invalid(value);
        Self(value)
    }

    /// Returns a new quantity with absolute value of `self`.
    pub fn abs(&self) -> Self {
        #[cfg(debug_assertions)]
        panic_on_invalid(self.0);
        Self::new(self.0.abs())
    }

    pub const fn inner(&self) -> f32 {
        self.0
    }
}

impl<const U: Unit> PartialEq for Quantity<U> {
    fn eq(&self, other: &Self) -> bool {
        #[cfg(debug_assertions)]
        panic_on_invalid(self.0);
        #[cfg(debug_assertions)]
        panic_on_invalid(other.0);
        self.0 == other.0
    }
}

impl<const U: Unit> From<Quantity<U>> for f32 {
    fn from(quantity: Quantity<U>) -> f32 {
        #[cfg(debug_assertions)]
        panic_on_invalid(quantity.0);
        quantity.0
    }
}

impl<const U: Unit> TryFrom<f32> for Quantity<U> {
    type Error = QuantityValueError;

    fn try_from(value: f32) -> Result<Self, Self::Error> {
        if value.is_nan() {
            Err(QuantityValueError::NaN)
        } else {
            Ok(Self(value))
        }
    }
}

impl<const U: Unit> Eq for Quantity<U> {}

impl<const U: Unit> PartialOrd for Quantity<U> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl<const U: Unit> Ord for Quantity<U> {
    fn cmp(&self, other: &Self) -> Ordering {
        #[cfg(debug_assertions)]
        panic_on_invalid(self.0);
        #[cfg(debug_assertions)]
        panic_on_invalid(other.0);
        self.0.partial_cmp(&other.0).unwrap()
    }
}

impl<const U: Unit> Neg for Quantity<U> {
    type Output = Self;

    fn neg(self) -> Self {
        #[cfg(debug_assertions)]
        panic_on_invalid(self.0);
        Self(-self.0)
    }
}

impl<const U: Unit> Add for Quantity<U> {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        #[cfg(debug_assertions)]
        panic_on_invalid(self.0);
        #[cfg(debug_assertions)]
        panic_on_invalid(other.0);
        Self(self.0 + other.0)
    }
}

impl<const U: Unit> Sub for Quantity<U> {
    type Output = Self;

    fn sub(self, other: Self) -> Self {
        #[cfg(debug_assertions)]
        panic_on_invalid(self.0);
        #[cfg(debug_assertions)]
        panic_on_invalid(other.0);
        Self(self.0 - other.0)
    }
}

impl<const U: Unit> AddAssign for Quantity<U> {
    fn add_assign(&mut self, other: Self) {
        #[cfg(debug_assertions)]
        panic_on_invalid(self.0);
        #[cfg(debug_assertions)]
        panic_on_invalid(other.0);
        self.0 += other.0;
    }
}

impl<const U: Unit> SubAssign for Quantity<U> {
    fn sub_assign(&mut self, other: Self) {
        #[cfg(debug_assertions)]
        panic_on_invalid(self.0);
        #[cfg(debug_assertions)]
        panic_on_invalid(other.0);
        self.0 -= other.0;
    }
}

impl<const U: Unit> Mul<f32> for Quantity<U> {
    type Output = Self;

    fn mul(self, rhs: f32) -> Self {
        Self::new(self.0 * rhs)
    }
}

impl<const U: Unit> Mul<Quantity<U>> for f32 {
    type Output = Quantity<U>;

    fn mul(self, rhs: Quantity<U>) -> Quantity<U> {
        Quantity::<U>::new(self * rhs.0)
    }
}

impl<const U: Unit> MulAssign<f32> for Quantity<U> {
    fn mul_assign(&mut self, rhs: f32) {
        self.0 *= rhs;
        panic_on_invalid(self.0);
    }
}

impl<const U: Unit> Div<f32> for Quantity<U> {
    type Output = Self;

    fn div(self, rhs: f32) -> Self {
        Self::new(self.0 / rhs)
    }
}

impl<const U: Unit> DivAssign<f32> for Quantity<U> {
    fn div_assign(&mut self, rhs: f32) {
        self.0 /= rhs;
        panic_on_invalid(self.0);
    }
}

#[inline]
fn panic_on_invalid(value: f32) {
    if value.is_nan() {
        panic!("Quantity cannot hold a NaN value");
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_new_unchecked() {
        let a: Quantity<1> = Quantity::new_unchecked(2.5);
        let b: Quantity<1> = Quantity::new_unchecked(-4.0);
        assert_eq!(f32::from(a), 2.5);
        assert_eq!(f32::from(b), -4.0);
    }

    #[test]
    fn test_new() {
        let q: Quantity<2> = Quantity::new(5.0);
        assert_eq!(f32::from(q), 5.0);
    }

    #[test]
    #[should_panic]
    fn test_new_panic() {
        Quantity::<3>::new(f32::NAN);
    }

    #[test]
    fn test_eq() {
        let a: Quantity<2> = Quantity::new(5.0);
        let b: Quantity<2> = Quantity::new(5.0);
        let c: Quantity<2> = Quantity::new(-5.0);
        assert_eq!(a, b);
        assert_ne!(b, c);
    }

    #[test]
    fn test_try_from() {
        let a: Quantity<17> = Quantity::try_from(5.5).unwrap();
        assert_eq!(f32::from(a), 5.5);
        let b: Result<Quantity<17>, QuantityValueError> = Quantity::try_from(f32::NAN);
        assert_eq!(b.err().unwrap(), QuantityValueError::NaN);
    }

    #[test]
    fn test_ord() {
        let a: Quantity<42> = Quantity::new(5.5);
        let b: Quantity<42> = Quantity::new(5.5);
        let c: Quantity<42> = Quantity::new(-5.5);
        assert_eq!(a.partial_cmp(&b).unwrap(), a.cmp(&b));
        assert_eq!(a.partial_cmp(&c).unwrap(), a.cmp(&c));
        assert_eq!(c.partial_cmp(&a).unwrap(), c.cmp(&a));
        assert_eq!(a.cmp(&b), Ordering::Equal);
        assert_eq!(a.cmp(&c), Ordering::Greater);
        assert_eq!(c.cmp(&a), Ordering::Less);
    }

    #[test]
    fn test_neg() {
        let a: Quantity<42> = -Quantity::new(69.42);
        assert_eq!(f32::from(a), -69.42);
    }

    #[test]
    fn test_add() {
        let a: Quantity<42> = Quantity::new(1.);
        let b: Quantity<42> = Quantity::new(-1.);
        assert_eq!(a + b, Quantity::<42>::ZERO);
        assert_eq!(f32::from(a + b), 0.);
    }

    #[test]
    fn test_sub() {
        let a: Quantity<42> = Quantity::new(1.);
        let b: Quantity<42> = Quantity::new(-1.);
        assert_eq!(f32::from(a - b), 2.);
    }

    #[test]
    fn test_add_assign() {
        let mut a: Quantity<42> = Quantity::new(1.);
        a += Quantity::new(3.);
        assert_eq!(f32::from(a), 4.);
    }

    #[test]
    fn test_sub_assign() {
        let mut a: Quantity<42> = Quantity::new(1.);
        a -= Quantity::new(3.);
        assert_eq!(f32::from(a), -2.);
    }

    #[test]
    fn test_mul_f32() {
        let a: Quantity<42> = Quantity::new(2.);
        assert_eq!(7.1 * a, a * 7.1);
        assert_eq!(f32::from(7.1 * a), 14.2);
    }

    #[test]
    fn test_mul_assign_f32() {
        let mut a: Quantity<42> = Quantity::new(3.);
        a *= 7.;
        assert_eq!(f32::from(a), 21.);
    }

    #[test]
    fn test_div_f32() {
        let a: Quantity<42> = Quantity::new(3.);
        assert_eq!(f32::from(a / 2.), 1.5);
    }

    #[test]
    fn test_div_assign_f32() {
        let mut a: Quantity<42> = Quantity::new(28.);
        a /= 7.;
        assert_eq!(f32::from(a), 4.);
    }
}