irox_tools/primitives/
u8.rs

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
// SPDX-License-Identifier: MIT
// Copyright 2023 IROX Contributors

//!
//! A collection of utilities for the u8 built-in
//!

use crate::{ToF64, WrappingAdd, WrappingMul, WrappingSub};

///
/// Finds the minimum and maximum value in the provided iterator.
/// Example:
/// ```
/// let values : Vec<u8> = vec![0, 5, 30, 20, 2];
/// let (min, max) = irox_tools::u8::min_max(&values);
///
/// assert_eq!(min, 0);
/// assert_eq!(max, 30);
/// ```
#[must_use]
pub fn min_max(iter: &[u8]) -> (u8, u8) {
    let mut min = u8::MAX;
    let mut max = u8::MIN;

    for val in iter {
        min = min.min(*val);
        max = max.max(*val);
    }

    (min, max)
}

impl WrappingAdd for u8 {
    fn wrapping_add(&self, rhs: Self) -> Self {
        u8::wrapping_add(*self, rhs)
    }
}
impl WrappingAdd for i8 {
    fn wrapping_add(&self, rhs: Self) -> Self {
        i8::wrapping_add(*self, rhs)
    }
}
impl WrappingSub for u8 {
    fn wrapping_sub(&self, rhs: Self) -> Self {
        u8::wrapping_sub(*self, rhs)
    }
}
impl WrappingSub for i8 {
    fn wrapping_sub(&self, rhs: Self) -> Self {
        i8::wrapping_sub(*self, rhs)
    }
}
impl WrappingMul for u8 {
    fn wrapping_mul(&self, rhs: Self) -> Self {
        u8::wrapping_mul(*self, rhs)
    }
}
impl WrappingMul for i8 {
    fn wrapping_mul(&self, rhs: Self) -> Self {
        i8::wrapping_mul(*self, rhs)
    }
}
impl ToF64 for u8 {
    fn to_f64(&self) -> f64 {
        *self as f64
    }
}
impl ToF64 for i8 {
    fn to_f64(&self) -> f64 {
        *self as f64
    }
}