Macro konst::const_cmp_for

source ·
macro_rules! const_cmp_for {
    (
        slice;
        $left_slice:expr,
        $right_slice:expr
        $(, $($comparison:tt)* )?
    ) => { ... };
    (
        option;
        $left_opt:expr,
        $right_opt:expr
        $(, $($comparison:tt)* )?
    ) => { ... };
}
Expand description

Compares two standard library types for ordering, that can’t be compared with const_cmp.

This macro takes the same types (except for range types), has the same limitations, and takes arguments of the same form as the const_eq_for macro

§Examples

§Slices

use konst::{const_cmp, const_cmp_for, try_equal};

use std::cmp::Ordering;

const fn cmp_slice_pair(left: &[(u32, u32)], right: &[(u32, u32)]) -> Ordering {
    const_cmp_for!(slice; left, right, |l, r|{
        try_equal!(const_cmp!(l.0, r.0));
        try_equal!(const_cmp!(l.1, r.1))
    })
}

const _: () = {
    let foo = &[(0, 1), (1, 2), (3, 4), (5, 6)];
    let bar = &[(0, 1), (3, 4), (5, 6), (7, 8)];

    assert!(matches!(cmp_slice_pair(foo, foo), Ordering::Equal));
    assert!(matches!(cmp_slice_pair(foo, bar), Ordering::Less));
    assert!(matches!(cmp_slice_pair(bar, foo), Ordering::Greater));
    assert!(matches!(cmp_slice_pair(bar, bar), Ordering::Equal));
};

§Options

use konst::{const_cmp, const_cmp_for, try_equal};

use std::cmp::Ordering;

#[derive(Copy, Clone)]
enum Shape {
    Square,
    Circle,
    Line,
}

const fn cmp_opt_pair(left: Option<Shape>, right: Option<Shape>) -> Ordering {
    const_cmp_for!(option; left, right, |x| *x as u8 )
}

const _: () = {
    let foo = Some(Shape::Square);
    let bar = Some(Shape::Circle);
    let baz = Some(Shape::Line);

    assert!(matches!(cmp_opt_pair(foo, foo), Ordering::Equal));
    assert!(matches!(cmp_opt_pair(foo, bar), Ordering::Less));
    assert!(matches!(cmp_opt_pair(foo, baz), Ordering::Less));

    assert!(matches!(cmp_opt_pair(bar, foo), Ordering::Greater));
    assert!(matches!(cmp_opt_pair(bar, bar), Ordering::Equal));
    assert!(matches!(cmp_opt_pair(bar, baz), Ordering::Less));

    assert!(matches!(cmp_opt_pair(baz, foo), Ordering::Greater));
    assert!(matches!(cmp_opt_pair(baz, bar), Ordering::Greater));
    assert!(matches!(cmp_opt_pair(baz, baz), Ordering::Equal));
};