Macro Syntax Variable Len

I have found that sometimes it is very useful to know how many repetitions have been collected into a macro syntax variable. This is even something that has been asked about online. (See here as an example).

The method works, but smells of some of the problems of the C pre-processor and the sort of “hacks” that are required when working in that language.

Proposal:

Add a len() “method” on syntax variables for macro expansion.

Usage:

Example:

macro_rules! foo {
    ($($items),*) => (
        $$len($items)
    );
}

// in function
foo!("1", a, 8, true) // == 4usize

Alternatives:

  • Do nothing, the problem is actually currently solvable
1 Like
macro_rules! len {
    () => { 0 };
    ($($i:tt $j:tt)*) => { len!($($i)*) * 2 };
    ($j:tt $($i:tt)*) => { len!($($i)*) + 1 };
}

fn main() {
    assert_eq!(5, len!(0 0 0 0 0));
    assert_eq!(3, len!(0 0 0));
    assert_eq!(10, len!(0 0 0 0 0 0 0 0 0 0));
    assert_eq!(0, len!());
    assert_eq!(11, len!(0 0 0 0 0 0 0 0 0 0 0));
}

If you want to count a comma separated list

macro_rules! len {
    () => { 0 };
    ($($i:expr, $j:expr),* $(,)?) => { len!($($i),*) * 2 };
    ($j:expr $(,$i:expr)* $(,)?) => { len!($($i),*) + 1 };
}

This post you linked is old and out dated.

5 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.