使用旧的 Rust 2015
| 1.0.0 |
|
|---|
#29 in #cleaner
7KB
89 代码行
wrapping_macros
一个用于作用域封装算术的宏。
在 wrapping! { .. } 块内的任何代码将被转换如下
a + b变为a.wrapping_add(b). 类似地,对于-、*、/、%、<<、>>。a += b变为a = a.wrapping_add(b). 类似地,对于-=、*=、/=、%=、<<=、>>=。-a变为a.wrapping_neg().
Cargo
将此添加到您的 Cargo.toml
wrapping_macros = "*"
示例
let a = 128u8;
let b = wrapping! { a * 2 };
assert_eq!(b, 0);
let mut a = 250u8;
let mut b = 4u8;
let mut c = 100u8;
wrapping! {
a += 10;
b -= 10;
c *= 10;
}
assert_eq!(a, 4);
assert_eq!(b, 250);
assert_eq!(c, 232);
use wrapping_macros::wrapping;
fn main() {
let mut sum = 0u8;
wrapping! {
for x in 0u8..50 {
sum += x;
}
}
}
assert_eq!(sum, 201);
注意事项
您不能在 wrapping! 块内嵌套另一个宏调用。例如,这不会起作用
let x = 128u8;
wrapping! {
println!("The answer is {}", x + 128) // Error
}
相反,将宏调用移出 wrapping! 块
let x = 128u8;
println!("The answer is {}", wrapping! { x + 128 })
灵感来源于 lfairy 的 wrapping_macros 包
依赖项
~1.5MB
~36K SLoC