Skip to content

Instantly share code, notes, and snippets.

@archshift
Created February 9, 2016 10:41
Show Gist options
  • Save archshift/786d6ae9cb8bfbca74df to your computer and use it in GitHub Desktop.
Save archshift/786d6ae9cb8bfbca74df to your computer and use it in GitHub Desktop.
macro_rules! extract_bits {
($val:expr, $low:expr => $hi:expr) => {{
let max_bit = std::mem::size_of_val(&$val) * 8 - 1;
assert!((($hi as usize) <= max_bit) && ($low >= 0));
$val << (max_bit - $hi) >> (max_bit - $hi + $low)
}};
}
macro_rules! create_bitfield {
($name:ident: $ty:ty, { $($var_name:ident: $var_low:expr => $var_hi:expr),* }) => {
#[derive(Debug)]
struct $name {
val: $ty,
}
impl $name {
fn new(val: $ty) -> $name {
$name {
val: val,
}
}
$(
#[inline]
fn $var_name(&self) -> $ty {
extract_bits!(self.val, $var_low => $var_hi)
}
)*
}
};
}
create_bitfield!(RAND: u32, {
foo: 0 => 6,
bar: 7 => 24,
foobar: 25 => 31
});
fn main() {
let val = 0xABCDEF12;
let val_bf = RAND::new(val);
println!("{:#X}", val);
println!("{:#b}", val);
println!("{:#b}", val_bf.foo());
println!("{:#b}", val_bf.bar());
println!("{:#b}", val_bf.foobar());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment