#wrapping #arithmetic #macro #version

nightly wrapping_macros

A macro for wrapping arithmetic

17 releases

Uses old Rust 2015

0.4.13 Jul 16, 2017
0.4.12 Jan 26, 2017
0.4.11 Nov 23, 2016
0.4.9 Jul 10, 2016
0.4.1 Jul 10, 2015

#1496 in Rust patterns

23 downloads per month

MIT/Apache

7KB
94 lines

wrapping_macros Build Status Cargo

A macro for wrapping arithmetic.

Any code within a wrapping! { .. } block will be transformed as follows:

  • a + b becomes a.wrapping_add(b). Similarly for -, *, /, %, <<, >>.
  • a += b becomes a = a.wrapping_add(b). Similarly for -=, *=, /=, %=, <<=, >>=.
  • -a becomes a.wrapping_neg().

See this Internals thread for the motivation behind this crate.

Note: This crate uses internal compiler APIs, and so requires the Nightly version of Rust.

Cargo

Add this to your Cargo.toml:

wrapping_macros = "*"

Example

#![feature(plugin)]
#![plugin(wrapping_macros)]

fn main() {
    let mut sum = 0u8;
    for x in 0u8..50 {
        wrapping! {
            sum += x;
        }
    }
}

Caveats

  • This crate uses unstable APIs, and will only work on Rust Nightly.

  • You cannot nest another macro invocation within a wrapping! block. For example, this will not work:

    let x = 41i32;
    wrapping! {
        println!("The answer is {}", x + 1);  //~ ERROR
    }
    

    Instead, move the macro call out of the block:

    let x = 41i32;
    println!("The answer is {}", wrapping! { x + 1 });
    

No runtime deps