Macro core_extensions::count_tts
source · macro_rules! count_tts { ($parentheses:tt) => { ... }; ($($everything:tt)*) => { ... }; }
Expand description
Counts the amount of token trees passed to this macro, passing the amount to an (optional) callback macro.
Note that macro parameters (eg: $foo
) are one token tree,
and matched pairs of []
/()
/{}
count as one token tree regardless of
the tokens inside.
§Callback
You need to pass a callback macro whenever the macro expects a literal.
If you only need the count for an expression(ie: the length of an array), then no callback macro is necessary.
§Version compatibility
This macro requires Rust 1.45.0 to be invoked with a callback parameter, inside an expression.
§Example
use core_extensions::count_tts;
fn main() {
// The counted tokens must be wrapped in parentheses,
// otherwise passing a callback macro would be syntactically ambiguous.
assert_eq!(count_tts!(()), 0);
assert_eq!(count_tts!((zero)), 1);
assert_eq!(count_tts!((zero one)), 2);
assert_eq!(count_tts!((zero (one two three) four)), 3);
assert_eq!(hello(), "hello");
}
macro_rules! expects_5{
(
foo $ident:ident baz
5
) => {
fn $ident() -> &'static str {
stringify!($ident)
}
}
}
// Calls the `expects_5` macro.
count_tts!{
// The invoked macro, and the first arguments passed to it
expects_5!{foo hello baz}
// The token trees to count
(a [b c d] (e f) {g h i} 10 )
}