Idiomatic way to implement u8 bit utils

I'd probably make an extension trait and use |= and &=. Furthermore, get doesn't really need to take a reference and it doesn't need the explicit mask, either:

trait BitExt {
    fn get(self, n: usize) -> bool;
    fn set(&mut self, n: usize);
    fn clear(&mut self, n: usize);
}

impl BitExt for u8 {
    fn get(self, n: usize) -> bool {
        (self >> n) & 1 == 1
    }

    fn set(&mut self, n: usize) {
        *self |= 1 << n;
    }

    fn clear(&mut self, n: usize) {
        *self &= !(1 << n);
    }
}
1 Like