syntactic-for
A syntactic "for" loop Rust macro.
For example, the following takes the sum of the bit-length of four integer types:
let sum = syntactic_for!;
assert_eq!;
Usage
The syntax is as follows:
syntactic_for!
where BODY
works similarly to macro_rules!
, that is:
$($IDENTIFIER)SEPARATOR*
will expand and substitute IDENTIFIER
with
each EXPRESSION
, separating the expansions with SEPARATOR
.
SEPARATOR
can be any non-*
punctuation. Hence, the example from above
could also be written without an iterator:
$+*
Examples
Loop unrolling
Sum the elements of an array with loop unrolling:
let array = b"oh my, I am getting summed!";
let mut acc = 0u32;
let mut i = 0;
while i <= array.len-4
for j in i..array.len
assert_eq!;
Matching
Find the maximum value of an integer type of the given bit size:
let max_size = syntactic_for!;
impl
blocks
Implement a trait for a set of types:
syntactic_for!
Custom syntactic loop
A useful design pattern is to define a custom macro that expands to a syntactic loop over a given set of expressions:
pub extern crate syntactic_for;
For example, a library could expose for_each_custom_type
as a way of
letting its users write syntactic loops over a set of types defined in the
library. Then, it becomes possible to add types to that loop inside the
library, whithout requiring any change on the user's end:
// Try and parse each library type in succession, stopping at the first
// success: