Last active
August 26, 2020 17:03
-
-
Save sashka/41e38ab865b53cb9884c472e3d7cda5e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// The `iota_const!` macro constructs a sequence of constants of a given type, starting with `1 << 0`. | |
/// Usage: | |
/// `iota_const!(u8, A, B, C); | |
/// Will generate: | |
/// pub const A: u8 = 1 << 0; // 1 << 0 | |
/// pub const B: u8 = 1 << 0+1; // 1 << 1 | |
/// pub const C: u8 = 1 << 0+1+1; // 1 << 2 | |
macro_rules! iota_const { | |
// There's no way to iterate over the args, so I need to run private macro recirsively | |
// to accumulate a counter expression like `(0+1+...+1)`. | |
( $const_type:ty, $name:ident, $( $rest:tt )* )=> { | |
__iota_const_impl!($const_type, (0), $name, $( $rest )*); | |
}; | |
} | |
macro_rules! __iota_const_impl { | |
( $const_type:ty, ($i:expr), $name:ident, $( $rest:tt )+ ) => { | |
pub const $name: $const_type = 1<<($i); | |
__iota_const_impl!($const_type, ($i+1), $( $rest )+); | |
}; | |
( $const_type:ty, ($i:expr), $name:ident, $last:ident ) => { | |
pub const $name: $const_type = 1<<($i); | |
__iota_const_impl!($const_type, ($i+1), $last); | |
}; | |
( $const_type:ty, ($i:expr), $name:ident ) => { | |
pub const $name: $const_type = 1<<($i); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment