Skip to content

Instantly share code, notes, and snippets.

@paavohuhtala
Created January 12, 2017 00:59
Show Gist options
  • Save paavohuhtala/336f005b4241064bb6b343da92c61fd7 to your computer and use it in GitHub Desktop.
Save paavohuhtala/336f005b4241064bb6b343da92c61fd7 to your computer and use it in GitHub Desktop.
Rust macro issue, "no rules expected the token `2`"
macro_rules! field_size {
(1) => (bool);
(2) => (u8);
(3) => (u8);
(4) => (u8);
(5) => (u8);
(6) => (u8);
(7) => (u8);
(8) => (u8);
}
macro_rules! size_mask {
(1) => (0b1);
(2) => (0b11);
(3) => (0b111);
(4) => (0b1111);
(5) => (0b1_1111);
(6) => (0b11_1111);
(7) => (0b111_1111);
(8) => (0b1111_1111);
}
macro_rules! bit_struct {
(@field $name: ident, $size: expr, $offset: expr) => {
pub fn $name(self) -> field_size!($size) {
let mask = (size_mask!($size)) << $offset;
let value = ((self.0 & mask) >> $offset) as field_size!($size);
value
}
};
(@fields $offset: expr, []) => {};
(@fields $offset: expr, [$name: ident($size: expr), $($tail_name: ident($tail_size:expr)),*]) => {
bit_struct!(@field $name, $size, ($offset + $size));
bit_struct!(@fields ($offset + $size), [$($tail_name($tail_size)),*]);
};
{ struct $struct_name: ident : $_repr_: ident {
$($name: ident($size: expr)),+
}
} => {
pub struct $struct_name ($_repr_);
impl $struct_name {
bit_struct!(@fields 0usize, [$($name($size)),+]);
}
}
}
const x : field_size!(6) = size_mask!(2);
bit_struct! {
struct Palette: u8 {
palette_0(2),
palette_1(2),
palette_2(2),
palette_3(2)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment