1 unstable release

0.2.0 Sep 10, 2020

#96 in #comparison

Download history 2/week @ 2024-03-26 25/week @ 2024-04-02 1/week @ 2024-04-09 29/week @ 2024-04-16 2/week @ 2024-05-14 15/week @ 2024-05-21 16/week @ 2024-05-28 13/week @ 2024-06-04 117/week @ 2024-06-11 9/week @ 2024-06-18 66/week @ 2024-06-25

221 downloads per month

GPL-3.0-only

9KB
73 lines

chain_cmp

Use the chmp! macro to chain comparison operators like you can in Python, for example.

You can use all of these operators <, <=, >, >=, ==, != inside a chmp! invocation.

Examples

Basic usage

use chain_cmp::chmp;

let (a, b, c) = (1, 2, 3);

let verbose = a < b && b <= c;
let concise = chmp!(a < b <= c);
assert_eq!(concise, verbose);

// You can use equality operators as well:
assert!(chmp!(a != b != c));

// And you can even chain more than three operators:
assert!(chmp!(a != b != c != a)); // making sure these values are pairwise distinct

// And of course mix and match operators:
assert!(chmp!(a < b <= c != a == a));

Short-circuiting

chmp! will short-circuit to evaluate the fewest expressions possible.

fn panics() -> i32 {
    panic!();
}

assert!(!chmp!(i32::MAX < i32::MIN < panics())); // this **won't** panic

Comparing arbitrary expressions

As long as the comparison operators have the lowest precedence, chmp! will evaluate any expression, like variables, blocks, function calls, etc.

const ANSWER: u32 = 42;

assert!(chmp!({
    println!("Life, the Universe, and Everything");
    ANSWER
} != 6 * 9 == 54));

Dependencies

~1.5MB
~35K SLoC