diff --git a/src/int.rs b/src/int.rs index e3ca72c0..ec4d6d12 100644 --- a/src/int.rs +++ b/src/int.rs @@ -52,6 +52,17 @@ pub trait PrimInt: + CheckedDiv + Saturating { + /// The size of this integer type in bits. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// assert_eq!(::BITS, 64); + /// ``` + const BITS: u32; + /// Returns the number of ones in the binary representation of `self`. /// /// # Examples @@ -394,6 +405,8 @@ fn reverse_bits_fallback(i: P) -> P { macro_rules! prim_int_impl { ($T:ty, $S:ty, $U:ty) => { impl PrimInt for $T { + const BITS: u32 = <$T>::BITS; + #[inline] fn count_ones(self) -> u32 { <$T>::count_ones(self) @@ -513,6 +526,20 @@ prim_int_impl!(isize, isize, usize); mod tests { use crate::int::PrimInt; + #[test] + pub fn bits() { + assert_eq!(::BITS, 8); + assert_eq!(::BITS, 8); + assert_eq!(::BITS, 16); + assert_eq!(::BITS, 16); + assert_eq!(::BITS, 32); + assert_eq!(::BITS, 32); + assert_eq!(::BITS, 64); + assert_eq!(::BITS, 64); + assert_eq!(::BITS, 128); + assert_eq!(::BITS, 128); + } + #[test] pub fn reverse_bits() { use core::{i16, i32, i64, i8};