rust-num / num-traits

Numeric traits for generic mathematics in Rust
Apache License 2.0
699 stars 131 forks source link

[feature request] Bits trait #247

Open kyp44 opened 2 years ago

kyp44 commented 2 years ago

Most Rust primitives have a BITS associated const (with the number of bits used), but evidently there is no way to use this generically. I have a particular need for this and it's easy enough to implement myself, but it seems like a good candidate for a num-traits trait.

kyp44 commented 2 years ago

Though this is obviously pretty trivial to figure out, here is an example for a subset of primitives.

pub trait Bits {
    fn bits() -> u32;
}
impl Bits for u8 {
    fn bits() -> u32 {
        Self::BITS
    }
}
impl Bits for u16 {
    fn bits() -> u32 {
        Self::BITS
    }
}
impl Bits for u32 {
    fn bits() -> u32 {
        Self::BITS
    }
}
impl Bits for u64 {
    fn bits() -> u32 {
        Self::BITS
    }
}