irox_tools/primitives/
u8.rs

1// SPDX-License-Identifier: MIT
2// Copyright 2023 IROX Contributors
3
4//!
5//! A collection of utilities for the u8 built-in
6//!
7
8use crate::{ToF64, WrappingAdd, WrappingMul, WrappingSub};
9
10///
11/// Finds the minimum and maximum value in the provided iterator.
12/// Example:
13/// ```
14/// let values : Vec<u8> = vec![0, 5, 30, 20, 2];
15/// let (min, max) = irox_tools::u8::min_max(&values);
16///
17/// assert_eq!(min, 0);
18/// assert_eq!(max, 30);
19/// ```
20#[must_use]
21pub fn min_max(iter: &[u8]) -> (u8, u8) {
22    let mut min = u8::MAX;
23    let mut max = u8::MIN;
24
25    for val in iter {
26        min = min.min(*val);
27        max = max.max(*val);
28    }
29
30    (min, max)
31}
32
33impl WrappingAdd for u8 {
34    fn wrapping_add(&self, rhs: Self) -> Self {
35        u8::wrapping_add(*self, rhs)
36    }
37}
38impl WrappingAdd for i8 {
39    fn wrapping_add(&self, rhs: Self) -> Self {
40        i8::wrapping_add(*self, rhs)
41    }
42}
43impl WrappingSub for u8 {
44    fn wrapping_sub(&self, rhs: Self) -> Self {
45        u8::wrapping_sub(*self, rhs)
46    }
47}
48impl WrappingSub for i8 {
49    fn wrapping_sub(&self, rhs: Self) -> Self {
50        i8::wrapping_sub(*self, rhs)
51    }
52}
53impl WrappingMul for u8 {
54    fn wrapping_mul(&self, rhs: Self) -> Self {
55        u8::wrapping_mul(*self, rhs)
56    }
57}
58impl WrappingMul for i8 {
59    fn wrapping_mul(&self, rhs: Self) -> Self {
60        i8::wrapping_mul(*self, rhs)
61    }
62}
63impl ToF64 for u8 {
64    fn to_f64(&self) -> f64 {
65        *self as f64
66    }
67}
68impl ToF64 for i8 {
69    fn to_f64(&self) -> f64 {
70        *self as f64
71    }
72}