src/math/traits.rs 9.6 KiB raw
1
//! Numerical traits.
2
#![allow(missing_docs, clippy::useless_nonzero_new_unchecked)]
3
use std::num::NonZeroU8;
4
use std::ops::{Add, Div, Mul, Neg, Shl, Sub};
5
6
/// A type that has a "zero".
7
pub trait Zero: PartialEq + Sized {
8
    const ZERO: Self;
9
10
    fn is_zero(&self) -> bool;
11
}
12
13
impl Zero for f32 {
14
    const ZERO: f32 = 0.;
15
16
    fn is_zero(&self) -> bool {
17
        self == &Self::ZERO
18
    }
19
}
20
21
impl Zero for f64 {
22
    const ZERO: f64 = 0.;
23
24
    fn is_zero(&self) -> bool {
25
        self == &Self::ZERO
26
    }
27
}
28
29
impl Zero for usize {
30
    const ZERO: usize = 0;
31
32
    fn is_zero(&self) -> bool {
33
        self == &Self::ZERO
34
    }
35
}
36
37
impl Zero for i32 {
38
    const ZERO: i32 = 0;
39
40
    fn is_zero(&self) -> bool {
41
        self == &Self::ZERO
42
    }
43
}
44
45
impl Zero for u8 {
46
    const ZERO: u8 = 0;
47
48
    fn is_zero(&self) -> bool {
49
        self == &Self::ZERO
50
    }
51
}
52
53
impl Zero for u16 {
54
    const ZERO: u16 = 0;
55
56
    fn is_zero(&self) -> bool {
57
        self == &Self::ZERO
58
    }
59
}
60
61
impl Zero for u32 {
62
    const ZERO: u32 = 0;
63
64
    fn is_zero(&self) -> bool {
65
        self == &Self::ZERO
66
    }
67
}
68
69
impl Zero for u64 {
70
    const ZERO: u64 = 0;
71
72
    fn is_zero(&self) -> bool {
73
        self == &Self::ZERO
74
    }
75
}
76
77
impl Zero for i64 {
78
    const ZERO: i64 = 0;
79
80
    fn is_zero(&self) -> bool {
81
        self == &Self::ZERO
82
    }
83
}
84
85
////////////////////////////////////////////////////////////////////////////////
86
87
/// A type that has a "one".
88
pub trait One: Sized {
89
    const ONE: Self;
90
91
    fn is_one(&self) -> bool;
92
}
93
94
impl One for f32 {
95
    const ONE: f32 = 1.;
96
97
    fn is_one(&self) -> bool {
98
        self == &Self::ONE
99
    }
100
}
101
102
impl One for f64 {
103
    const ONE: f64 = 1.;
104
105
    fn is_one(&self) -> bool {
106
        self == &Self::ONE
107
    }
108
}
109
110
impl One for usize {
111
    const ONE: usize = 1;
112
113
    fn is_one(&self) -> bool {
114
        self == &Self::ONE
115
    }
116
}
117
118
impl One for u8 {
119
    const ONE: u8 = 1;
120
121
    fn is_one(&self) -> bool {
122
        self == &Self::ONE
123
    }
124
}
125
126
impl One for u32 {
127
    const ONE: u32 = 1;
128
129
    fn is_one(&self) -> bool {
130
        self == &Self::ONE
131
    }
132
}
133
134
impl One for u64 {
135
    const ONE: u64 = 1;
136
137
    fn is_one(&self) -> bool {
138
        self == &Self::ONE
139
    }
140
}
141
142
impl One for i32 {
143
    const ONE: i32 = 1;
144
145
    fn is_one(&self) -> bool {
146
        self == &Self::ONE
147
    }
148
}
149
150
impl One for NonZeroU8 {
151
    const ONE: NonZeroU8 = unsafe { NonZeroU8::new_unchecked(u8::ONE) };
152
153
    fn is_one(&self) -> bool {
154
        self == &Self::ONE
155
    }
156
}
157
158
////////////////////////////////////////////////////////////////////////////////
159
160
/// A type that has a "two".
161
pub trait Two {
162
    const TWO: Self;
163
}
164
165
impl Two for f32 {
166
    const TWO: f32 = 2.;
167
}
168
169
impl Two for f64 {
170
    const TWO: f64 = 2.;
171
}
172
173
impl Two for i32 {
174
    const TWO: i32 = 2;
175
}
176
177
////////////////////////////////////////////////////////////////////////////////
178
179
/// Trait for types with defined minimum and maximum bounds.
180
pub trait Bounded {
181
    /// Minimum value for this type.
182
    const MIN: Self;
183
    /// Maximum value for this type.
184
    const MAX: Self;
185
}
186
187
impl Bounded for u8 {
188
    const MIN: Self = u8::MIN;
189
    const MAX: Self = u8::MAX;
190
}
191
192
impl Bounded for u16 {
193
    const MIN: Self = u16::MIN;
194
    const MAX: Self = u16::MAX;
195
}
196
197
impl Bounded for u32 {
198
    const MIN: Self = u32::MIN;
199
    const MAX: Self = u32::MAX;
200
}
201
202
impl Bounded for u64 {
203
    const MIN: Self = u64::MIN;
204
    const MAX: Self = u64::MAX;
205
}
206
207
impl Bounded for i8 {
208
    const MIN: Self = i8::MIN;
209
    const MAX: Self = i8::MAX;
210
}
211
212
impl Bounded for i16 {
213
    const MIN: Self = i16::MIN;
214
    const MAX: Self = i16::MAX;
215
}
216
217
impl Bounded for i32 {
218
    const MIN: Self = i32::MIN;
219
    const MAX: Self = i32::MAX;
220
}
221
222
impl Bounded for i64 {
223
    const MIN: Self = i64::MIN;
224
    const MAX: Self = i64::MAX;
225
}
226
227
impl Bounded for f64 {
228
    const MIN: Self = f64::MIN;
229
    const MAX: Self = f64::MAX;
230
}
231
232
impl Bounded for f32 {
233
    const MIN: Self = f32::MIN;
234
    const MAX: Self = f32::MAX;
235
}
236
237
impl Bounded for usize {
238
    const MIN: Self = usize::MIN;
239
    const MAX: Self = usize::MAX;
240
}
241
242
////////////////////////////////////////////////////////////////////////////////
243
244
/// Trait defining operations and properties required for integer types.
245
pub trait Integer:
246
    Copy
247
    + Ord
248
    + One
249
    + Zero
250
    + Bounded
251
    + Add<Output = Self>
252
    + Sub<Output = Self>
253
    + Shl<u32, Output = Self>
254
{
255
    /// Number of bits in this integer type.
256
    const BITS: u32;
257
258
    /// Converts a [`u64`] to this integer type.
259
    fn from_u64(other: u64) -> Self;
260
    /// Converts this integer to [`u64`].
261
    fn as_u64(&self) -> u64;
262
    /// Wrapping add.
263
    fn wrapping_add(self, rhs: Self) -> Self;
264
    /// Wrapping sub.
265
    fn wrapping_sub(self, rhs: Self) -> Self;
266
}
267
268
impl Integer for u32 {
269
    const BITS: u32 = u32::BITS;
270
271
    fn from_u64(other: u64) -> Self {
272
        other as u32
273
    }
274
275
    fn as_u64(&self) -> u64 {
276
        *self as u64
277
    }
278
279
    fn wrapping_add(self, rhs: Self) -> Self {
280
        self.wrapping_add(rhs)
281
    }
282
283
    fn wrapping_sub(self, rhs: Self) -> Self {
284
        self.wrapping_sub(rhs)
285
    }
286
}
287
288
impl Integer for i32 {
289
    const BITS: u32 = i32::BITS;
290
291
    fn from_u64(other: u64) -> Self {
292
        other as u32 as i32
293
    }
294
295
    fn as_u64(&self) -> u64 {
296
        *self as u32 as u64
297
    }
298
299
    fn wrapping_add(self, rhs: Self) -> Self {
300
        self.wrapping_add(rhs)
301
    }
302
303
    fn wrapping_sub(self, rhs: Self) -> Self {
304
        self.wrapping_sub(rhs)
305
    }
306
}
307
308
impl Integer for u64 {
309
    const BITS: u32 = u64::BITS;
310
311
    fn from_u64(other: u64) -> Self {
312
        other
313
    }
314
315
    fn as_u64(&self) -> u64 {
316
        *self
317
    }
318
319
    fn wrapping_add(self, rhs: Self) -> Self {
320
        self.wrapping_add(rhs)
321
    }
322
323
    fn wrapping_sub(self, rhs: Self) -> Self {
324
        self.wrapping_sub(rhs)
325
    }
326
}
327
328
impl Integer for usize {
329
    const BITS: u32 = usize::BITS;
330
331
    fn from_u64(other: u64) -> Self {
332
        other as usize
333
    }
334
335
    fn as_u64(&self) -> u64 {
336
        *self as u64
337
    }
338
339
    fn wrapping_add(self, rhs: Self) -> Self {
340
        self.wrapping_add(rhs)
341
    }
342
343
    fn wrapping_sub(self, rhs: Self) -> Self {
344
        self.wrapping_sub(rhs)
345
    }
346
}
347
348
////////////////////////////////////////////////////////////////////////////////
349
350
/// Floating point numbers.
351
pub trait Float:
352
    Copy
353
    + PartialOrd
354
    + Zero
355
    + One
356
    + Two
357
    + Neg<Output = Self>
358
    + Add<Output = Self>
359
    + Sub<Output = Self>
360
    + Div<Output = Self>
361
    + Mul<Output = Self>
362
{
363
    /// Get the square root.
364
    fn sqrt(self) -> Self;
365
}
366
367
impl Float for f32 {
368
    fn sqrt(self) -> Self {
369
        f32::sqrt(self)
370
    }
371
}
372
373
impl Float for f64 {
374
    fn sqrt(self) -> Self {
375
        f64::sqrt(self)
376
    }
377
}
378
379
/// Adds convenience methods to `f32` and `f64`.
380
pub trait FloatExt<T> {
381
    /// Rounds to the nearest integer towards zero,
382
    /// unless the provided value is already an integer.
383
    ///
384
    /// It is to `floor` what `expand` is to `ceil`.
385
    ///
386
    /// # Examples
387
    ///
388
    /// ```
389
    /// use rustik::math::traits::FloatExt;
390
    ///
391
    /// let f = 3.7_f64;
392
    /// let g = 3.0_f64;
393
    /// let h = -3.7_f64;
394
    /// let i = -5.9_f32;
395
    ///
396
    /// assert_eq!(f.truncate(), 3.0);
397
    /// assert_eq!(g.truncate(), 3.0);
398
    /// assert_eq!(h.truncate(), -3.0);
399
    /// assert_eq!(i.truncate(), -5.0);
400
    /// ```
401
    fn truncate(&self) -> T;
402
403
    /// Rounds to the nearest integer away from zero,
404
    /// unless the provided value is already an integer.
405
    ///
406
    /// It is to `ceil` what `truncate` is to `floor`.
407
    ///
408
    /// # Examples
409
    ///
410
    /// ```
411
    /// use rustik::math::traits::FloatExt;
412
    ///
413
    /// let f = 3.7_f64;
414
    /// let g = 3.0_f64;
415
    /// let h = -3.7_f64;
416
    /// let i = -5.1_f32;
417
    ///
418
    /// assert_eq!(f.expand(), 4.0);
419
    /// assert_eq!(g.expand(), 3.0);
420
    /// assert_eq!(h.expand(), -4.0);
421
    /// assert_eq!(i.expand(), -6.0);
422
    /// ```
423
    fn expand(&self) -> T;
424
}
425
426
impl FloatExt<f64> for f64 {
427
    #[inline]
428
    fn expand(&self) -> f64 {
429
        self.abs().ceil().copysign(*self)
430
    }
431
432
    #[inline]
433
    fn truncate(&self) -> Self {
434
        self.abs().floor().copysign(*self)
435
    }
436
}
437
438
impl FloatExt<f32> for f32 {
439
    #[inline]
440
    fn expand(&self) -> f32 {
441
        self.abs().ceil().copysign(*self)
442
    }
443
444
    #[inline]
445
    fn truncate(&self) -> Self {
446
        self.abs().floor().copysign(*self)
447
    }
448
}
449
450
/// Approximate equality.
451
pub trait ApproxEq {
452
    type Epsilon: Copy + PartialOrd;
453
454
    /// Checks if `|x - y| <= epsilon`.
455
    fn approx_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool;
456
    /// Checks if `|x - y| > epsilon`.
457
    fn approx_neq(&self, other: &Self, epsilon: Self::Epsilon) -> bool {
458
        !self.approx_eq(other, epsilon)
459
    }
460
}
461
462
impl ApproxEq for f32 {
463
    type Epsilon = f32;
464
465
    fn approx_eq(&self, other: &Self, epsilon: f32) -> bool {
466
        (self - other).abs() <= epsilon
467
    }
468
}
469
470
impl ApproxEq for f64 {
471
    type Epsilon = f64;
472
473
    fn approx_eq(&self, other: &Self, epsilon: f64) -> bool {
474
        (self - other).abs() <= epsilon
475
    }
476
}
477
478
#[cfg(test)]
479
mod test {
480
    use super::*;
481
    use crate::math::macros::*;
482
483
    #[test]
484
    fn test_approx_eq() {
485
        assert_approx_eq!(1.0, 1.0, 0.0001);
486
        assert_approx_eq!(1.0, 1.001, 0.01);
487
        assert_approx_neq!(1.0, 1.001, 0.00000001);
488
    }
489
490
    #[test]
491
    fn test_integer_wrapping() {
492
        let max_u32 = u32::MAX;
493
        assert_eq!(max_u32.wrapping_add(1), 0);
494
        assert_eq!(0_u32.wrapping_sub(1), max_u32);
495
496
        let max_i32 = i32::MAX;
497
        assert_eq!(max_i32.wrapping_add(1), i32::MIN);
498
        assert_eq!(i32::MIN.wrapping_sub(1), i32::MAX);
499
    }
500
501
    #[test]
502
    fn test_integer_conversions() {
503
        assert_eq!(42_u32.as_u64(), 42_u64);
504
        assert_eq!(42_i32.as_u64(), 42_u64);
505
        assert_eq!(42_u64.as_u64(), 42_u64);
506
        assert_eq!(42_usize.as_u64(), 42_u64);
507
    }
508
}