Is there a better way to implement the following: ?
impl BitMapUtil {
pub fn get(x: &u8, n: usize) -> bool {
let mask = 1_u8 << n;
x & mask == mask}
pub fn set_true(x: &mut u8, n: usize) {
let mask = 1_u8 << n;
*x = *x | mask;}
pub fn set_false(x: &mut u8, n: usize) {
let mask = 1_u8 << n;
*x = *x & (!mask);}}
H2CO3
June 11, 2021, 11:46am
2
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
system
Closed
September 9, 2021, 11:47am
3
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.