#count #procedural #macro #compile-time

macro count-macro

A simple Rust macro to perform compile time counting

6 releases

0.2.3 Aug 22, 2024
0.2.2 May 21, 2022
0.2.1 Feb 22, 2022
0.1.1 Jan 9, 2022

#2160 in Procedural macros

Download history 14/week @ 2024-06-26 19/week @ 2024-07-03 15/week @ 2024-07-10 24/week @ 2024-07-17 49/week @ 2024-07-24 20/week @ 2024-07-31 19/week @ 2024-08-07 19/week @ 2024-08-14 149/week @ 2024-08-21 13/week @ 2024-08-28 6/week @ 2024-09-04 5/week @ 2024-09-11 27/week @ 2024-09-18 17/week @ 2024-09-25 7/week @ 2024-10-02 15/week @ 2024-10-09

67 downloads per month
Used in 2 crates (via bool_vec)

MIT license

10KB
107 lines

Count macro

A macro to allow for compile time counting

How to use this

Every instance of _int_ will be replaced with either a literal or an ident.

count_macro::count will panic in debug mode if counter exceeds usize.

If you wish to wrap to 0, please use count_macro::wrapping_count.

Examples

Ident to literal

use count_macro::count;

let a = count!(vec![_int_, _int_, _int_]);
assert_eq!(a, vec![0, 1, 2]);

Ident to ident

use count_macro::count;

count! {
    let a_int_ = "Hello";
    let a_int_ = "World";
}

assert_eq!(a0, "Hello");
assert_eq!(a1, "World");

In macro

use count_macro::count;

macro_rules! my_macro {
    ($($v:expr),*) => {
        count!{
            $(
                let _ = $v; // Ignoring $v

                println!("{}", _int_);
            )*
        }
    };
}

my_macro!('@', '@', '@', '@'); // Will print from 0 to 3

Multiple counters

with _int_countername_ you'll be able to create a new counter called "countername".

This won't be incremented by _int_ or any other counter such as _int_0_ or _int_x_.

use count_macro::count;

// With two different counters
// _int_ does not increment _int_name_
count! {
    let a_int_ = _int_name_;
    let a_int_ = _int_name_;
    let a_int_ = _int_name_;
}

assert_eq!(a0, 0);
assert_eq!(a1, 1);
assert_eq!(a2, 2);

Dependencies

~2.1–3MB
~54K SLoC