Macro konst::try_equal

source ·
macro_rules! try_equal {
    (break $ord:expr $(,)*) => { ... };
    ($ord:expr $(,)*) => { ... };
    (break; $ord:expr $(,)*) => { ... };
}
Expand description

Evaluates to $ord if it is Ordering::Equal, otherwise returns it from the enclosing function.

§Example

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

use std::cmp::Ordering;

struct Fields<'a> {
    first: &'a [u8; 4],
    second: bool,
    third: Option<&'static str>,
}

impl_cmp!{
    impl['a] Fields<'a>;
    pub const fn const_cmp(&self, other: &Self) -> Ordering {
        try_equal!(const_cmp!(self.first, other.first));
        try_equal!(const_cmp!(self.second, other.second));
        try_equal!(const_cmp!(self.third, other.third))
    }
}

const _: () = {
    let foo = Fields {
        first: &[3, 5, 8, 13],
        second: false,
        third: None,
    };
     
    let bar = Fields {
        first: &[5, 8, 13, 14],
        second: true,
        third: Some("what!?"),
    };
     
    assert!(matches!(const_cmp!(foo, foo), Ordering::Equal));
    assert!(matches!(const_cmp!(foo, bar), Ordering::Less));
    assert!(matches!(const_cmp!(bar, foo), Ordering::Greater));
    assert!(matches!(const_cmp!(bar, bar), Ordering::Equal));
};