Giter Site home page Giter Site logo

syntactic-for's Introduction

syntactic-for

crates.io docs.rs

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!{ ty in [ u8, u16, u32, u64 ] {
    [$( <$ty>::BITS ),*].into_iter().sum::<u32>()
}};
assert_eq!(sum, 120);

Usage

The syntax is as follows:

syntactic_for!{ IDENTIFIER in [ EXPRESSION, EXPRESSION, ... ] {
    BODY
}}

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:

$( <$ty>::BITS )+*

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 {
    syntactic_for!{ offset in [ 0, 1, 2, 3 ] {$(
        acc += array[i + $offset] as u32;
    )*}}
    i += 4;
}
for j in i..array.len() {
    acc += array[j] as u32;
}
assert_eq!(acc, 2366);

Matching

Find the maximum value of an integer type of the given bit size:

let max_size = syntactic_for!{ ty in [ u8, u16, u32, u64, u128 ] {
    match bit_size {
        $(<$ty>::BITS => <$ty>::MAX as u128,)*
        other => panic!("No integer of size {other}"),
    }
}};

impl blocks

Implement a trait for a set of types:

syntactic_for!{ ty in [ u8, u16, u32, u64, u128 ] {$(
    impl MyTrait for $ty {
        // snip.
    }
)*}}

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:

#[doc(hidden)]
pub extern crate syntactic_for;

#[macro_export]
macro_rules! for_each_custom_type {
    ($ident:ident { $($tt:tt)* }) => {
        $crate::syntactic_for::syntactic_for! { $ident in [
            $crate::CustomType1,
            $crate::CustomType2,
            // etc.
        ] { $($tt)* } }
    }
}

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:
fn can_parse(input: &str) -> bool {
    my_library::for_each_custom_type! { ty {
        $(if let Ok(parsed) = <$ty>::parse(input) {
            return true;
        })*
    }}
    return false;
}

syntactic-for's People

Contributors

xlambein avatar jneem avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.