Generic integer MAX

Hi,

I want to have a function generic over an integer type T, and be able to access its MIN/MAX constants. But apparently they're not bound to any trait.
Is there a way to access <T>::MAX where T: integer (sortof) ?

The standard library doesn't have numeric traits, but you can use the num crate's Bounded trait.

2 Likes

Oh nice, I just made my own crate for this, but using associated constants instead of methods. I guess it's useless, won't publish it.

Just in case someone wants to avoid importing a whole crate for this, and just copy/paste instead:

pub trait MinMax {
    const MIN: Self;
    const MAX: Self;
}

impl MinMax for u8 {
    const MIN: u8 = u8::MIN;
    const MAX: u8 = u8::MAX;
}

/* etc. */

#[cfg(test)]
mod tests {
    fn it_works<T>()
    where
        T: super::MinMax + std::fmt::Debug + std::cmp::Eq + std::ops::Div<Output = T>,
        std::num::Wrapping<T>: std::ops::Add<std::num::Wrapping<T>, Output = std::num::Wrapping<T>>,
    {
        // FIXME https://github.com/rust-lang/rust/issues/27739
        let one = T::MAX / T::MAX;

        assert_eq!(
            T::MIN,
            (std::num::Wrapping(T::MAX) + std::num::Wrapping(one)).0
        );
    }
    #[test]
    fn it_works_u8() {
        it_works::<u8>();
    }
/* etc. */
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.