allowance 0.10.0

Rust Datatype to representate the deviation of measures.
Documentation
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
use crate::{Measure, Unit};
use std::cmp::Ordering;
use std::convert::TryFrom;
use std::fmt::{Debug, Display, Formatter};
use std::num::{ParseFloatError, TryFromIntError};
use std::ops::{Add, AddAssign, Deref, Div, Mul, Neg, Sub, SubAssign};

///
/// # Measure32
///
/// A type to calculate lossless dimensions with a fixed precision.
/// All sizes are defined in the tenth fraction of `μ`:
///
///  * 10 = 1 μ
///  * 10_000  = 1 mm
///  * 10_000_000  = 1 m
///
/// The standard `Display::fmt`-methode represents the value in `mm`. The *alternate* Display
/// shows the `i32` value.
///
/// As 10_000 = 1 mm
///
/// ### Warning
/// Casting an `i64` into a `Measure32` can cause an `IntegerOverflow`-error similar to casting
/// a big `i64`-value into an `i32`. It's up to the programmer to omit these situation. Don't
/// try to store more then `+/- 214 meter` in a `Measure32`.
///
/// ### Example:
/// ```rust
///#     use allowance::Measure32;
///     let measure32 = Measure32::from(12.5);
///
///     assert_eq!(format!("{measure32}"),"12.5000");
///     assert_eq!(format!("{measure32:.2}"), "12.50");
///     assert_eq!(format!("{measure32:#}"), "125000");
/// ```
///
///

#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Measure32(i32);

impl Measure32 {
    pub const MY: i32 = 10;
    pub const MM: Measure32 = Measure32(1_000 * Self::MY);
    pub const ZERO: Measure32 = Measure32(0);
    /// Holds at maximum 214m
    pub const MAX: Measure32 = Measure32(i32::MAX);
    /// Holds at minimum -214m
    pub const MIN: Measure32 = Measure32(i32::MIN);

    pub fn as_i32(&self) -> i32 {
        self.0
    }

    #[inline]
    pub fn as_mm(&self) -> f64 {
        (self.0 as f64) / Unit::MM.multiply() as f64
    }

    /// Returns the value in the given `Unit`.
    pub fn as_prec(&self, unit: Unit) -> f64 {
        (self.0 as f64) / unit.multiply() as f64
    }

    /// Rounds to the given Unit.
    pub fn round(&self, unit: Unit) -> Self {
        if unit.multiply() == 0 {
            return *self;
        }
        let m = unit.multiply();
        let clip = self.0 as i64 % m;
        match m / 2 {
            _ if clip == 0 => *self, // don't round
            x if clip <= -x => Measure32::from(self.0 as i64 - clip - m),
            x if clip >= x => Measure32::from(self.0 as i64 - clip + m),
            _ => Measure32(self.0 - clip as i32),
        }
    }

    pub fn floor(&self, unit: Unit) -> Self {
        let val = self.0;
        let clip = val % unit.multiply() as i32;
        Measure32(val - clip)
    }
}

macro_rules! measure32_from_number {
    ($($typ:ident),+) => {
        $(
            impl From<$typ> for Measure32 {
                fn from(a: $typ) -> Self {
                    assert!(
                        a < i32::MAX as $typ && a > i32::MIN as $typ,
                        "i32 overflow, the source-type is beyond the limits of this type (Measure32)."
                    );
                    Self(a as i32)
                }
            }

            impl From<Measure32> for $typ {
                fn from(a: Measure32) -> Self {
                    a.0 as $typ
                }
            }

            impl Add<$typ> for Measure32 {
                type Output = Measure32;

                fn add(self, rhs: $typ) -> Self::Output {
                    Self(self.0 + (rhs as i32))
                }
            }

            impl AddAssign<$typ> for Measure32 {
                fn add_assign(&mut self, rhs: $typ) {
                    self.0 += (rhs as i32);
                }
            }

            impl Sub<$typ> for Measure32 {
                type Output = Measure32;

                fn sub(self, rhs: $typ) -> Self::Output {
                    Self(self.0 - (rhs as i32))
                }
            }

            impl Mul<$typ> for Measure32 {
                type Output = Measure32;

                fn mul(self, rhs: $typ) -> Self::Output {
                    Self(self.0 * (rhs as i32))
                }
            }

            impl Div<$typ> for Measure32 {
                type Output = Measure32;

                fn div(self, rhs: $typ) -> Self::Output {
                    Self(self.0 / (rhs as i32))
                }
            }
        )+
    }
}

measure32_from_number!(u64, u32, u16, u8, usize, i64, i32, i16, i8);

impl From<Unit> for Measure32 {
    fn from(unit: Unit) -> Self {
        Measure32::from(unit.multiply())
    }
}

impl From<f64> for Measure32 {
    fn from(f: f64) -> Self {
        assert!(
            f < i32::MAX as f64 && f > i32::MIN as f64,
            "i32 overflow, the f64 is beyond the limits of this type (Measure32)."
        );
        Self((f * Measure32::MM.as_i32() as f64) as i32)
    }
}

impl From<Measure32> for f64 {
    fn from(f: Measure32) -> Self {
        f.0 as f64 / Measure32::MM.as_i32() as f64
    }
}

impl From<Measure32> for Measure {
    fn from(m: Measure32) -> Self {
        Measure::from(m.0)
    }
}

impl TryFrom<&str> for Measure32 {
    type Error = ParseFloatError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Ok(Measure32::from(value.parse::<f64>()?))
    }
}

impl TryFrom<String> for Measure32 {
    type Error = ParseFloatError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Ok(Measure32::from(value.parse::<f64>()?))
    }
}

impl TryFrom<Measure> for Measure32 {
    type Error = TryFromIntError;

    fn try_from(value: Measure) -> Result<Self, Self::Error> {
        let v: i32 = value.as_i64().try_into()?;
        Ok(Measure32(v))
    }
}

impl Display for Measure32 {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let p = f.precision().map(|p| p.min(4)).unwrap_or(4);
        if f.alternate() {
            Display::fmt(&self.0, f)
        } else {
            let val = self.round(Unit::DYN(4 - p)).0;
            let n = if val.is_negative() { 6 } else { 5 };
            let mut s = format!("{val:0n$}");
            if p > 0 {
                s.insert(s.len() - 4, '.');
            }
            s.truncate(s.len() - (4 - p));
            write!(f, "{s}")
        }
    }
}

impl Debug for Measure32 {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let val = self.0;
        let n = if val.is_negative() { 6 } else { 5 };
        let mut m = format!("{val:0n$}");
        m.insert(m.len() - 4, '.');
        write!(f, "Measure32({})", m)
    }
}

impl Neg for Measure32 {
    type Output = Measure32;

    fn neg(self) -> Self::Output {
        Self(-self.0)
    }
}

impl Add for Measure32 {
    type Output = Measure32;

    fn add(self, rhs: Self) -> Self::Output {
        Self(self.0 + rhs.0)
    }
}

impl Add<Measure> for Measure32 {
    type Output = Measure;

    fn add(self, rhs: Measure) -> Self::Output {
        Measure::from(rhs.as_i64() + self.as_i32() as i64)
    }
}

impl AddAssign for Measure32 {
    fn add_assign(&mut self, rhs: Self) {
        self.0 += rhs.0;
    }
}

impl Sub for Measure32 {
    type Output = Measure32;

    fn sub(self, rhs: Self) -> Self::Output {
        Self(self.0 - rhs.0)
    }
}

impl SubAssign for Measure32 {
    fn sub_assign(&mut self, rhs: Self) {
        self.0 -= rhs.0;
    }
}

impl Mul for Measure32 {
    type Output = Measure32;

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

impl Div for Measure32 {
    type Output = Measure32;

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

impl Deref for Measure32 {
    type Target = i32;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl PartialOrd for Measure32 {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.0.partial_cmp(&other.0)
    }
}

impl Ord for Measure32 {
    fn cmp(&self, other: &Self) -> Ordering {
        self.0.cmp(&other.0)
    }
}

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

    #[test]
    fn cmp() {
        let s1 = Measure32(200000);
        let i1 = Measure32(190000);
        let s2 = Measure32::from(20.0);
        let i2 = Measure32::from(19.0);

        assert!(s1 > i1);
        assert_eq!(s1.partial_cmp(&i1).unwrap(), Ordering::Greater);
        assert_eq!(s1, s1);
        assert_eq!(s1.partial_cmp(&s1).unwrap(), Ordering::Equal);

        assert!(s2 > i2);
        assert_eq!(s2.partial_cmp(&i2).unwrap(), Ordering::Greater);
        assert_eq!(s2, s1);
        assert_eq!(s2.partial_cmp(&s1).unwrap(), Ordering::Equal);

        assert_eq!(i1.cmp(&s1), Ordering::Less);
        assert_eq!(i1.cmp(&i1), Ordering::Equal);
    }

    #[test]
    fn neg() {
        let m = -Measure32(232332);
        let n = Measure32(-232332);
        assert_eq!(n.0, m.0);
        assert_eq!(n, m);
    }

    #[test]
    fn round() {
        let m = Measure32(1234567);
        assert_eq!(Measure32(1234570), m.round(Unit::MY));
        assert_eq!(Measure32(1200000), m.round(Unit::CM));
        assert_eq!(Measure32(10_000_000), Measure32(9_999_000).round(Unit::MM));
        assert_eq!(Measure32(0), Measure32::from(-0.4993).round(Unit::MM));
        assert_eq!(Measure32(-4990), Measure32::from(-0.4993).round(Unit::MY));
        assert_eq!(Measure32(-10000), Measure32::from(-5000).round(Unit::MM));
        let m = Measure32::from(340.993);
        assert_eq!(10, Unit::DYN(1).multiply());
        assert_eq!(Measure32(3409930), m.round(Unit::DYN(1)));
        assert_eq!(100, Unit::DYN(2).multiply());
        assert_eq!(Measure32(3409900), m.round(Unit::DYN(2)));
        assert_eq!(1000, Unit::DYN(3).multiply());
        assert_eq!(Measure32(3410000), m.round(Unit::DYN(3)));
        assert_eq!(Measure32(3400000), m.floor(Unit::DYN(4)));
        assert_eq!(-340.000, -340.993_f64.floor());
        assert_eq!(
            Measure32(-3400000),
            Measure32::from(-340.993).floor(Unit::DYN(4))
        );
    }

    #[test]
    fn display() {
        let m = Measure32(12455);
        assert_eq!("1.2455", format!("{m}").as_str());
        assert_eq!("1.246", format!("{m:.3}").as_str());
        assert_eq!("1.2", format!("{m:.1}").as_str());
        assert_eq!("1.2455", format!("{m:.7}").as_str());
        assert_eq!("1", format!("{m:.0}").as_str());
        assert_eq!("-1.2455", format!("{:.7}", -m).as_str());
        let m = Measure32(-455);
        assert_eq!("-0.0455", format!("{m}").as_str());
        assert_eq!("-0.3450", format!("{}", Measure32(-3450)).as_str());
        assert_eq!("-455", format!("{m:#}").as_str());
        let m = Measure32::from(4566.4689);
        assert_eq!(format!("{m:.3}"), "4566.469");
        let m = Measure32::ZERO;
        assert_eq!(format!("{m:.2}"), "0.00");
    }

    #[test]
    fn min_max() {
        let max = Measure32::MAX;
        let min = Measure32::MIN;

        assert_eq!(max.0, 2147483647);
        assert_eq!(min.0, -2147483648);
        assert_eq!(format!("{max:.0}"), "214748");
    }

    #[test]
    fn as_prec() {
        let m = Measure32::from(12456.832);
        assert_eq!(m.as_prec(Unit::CM), 1245.6832);
        assert_eq!(m.as_prec(Unit::METER), 12.456832);
    }
}