konst

Macro const_cmp

Source
macro_rules! const_cmp {
    ($left:expr, $right:expr $(,)*) => { ... };
}
Expand description

Compares two values for ordering.

The arguments must implement the ConstCmp trait. Non-standard library types must define a const_cmp method taking a reference.

§Limitations

The arguments must be concrete types, and have a fully inferred type. eg: if you pass an integer literal it must have a suffix to indicate its type.

§Example

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

use std::cmp::Ordering;

struct Fields<'a> {
    foo: u32,
    bar: Option<bool>,
    baz: Ordering,
    qux: &'a str,
}

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

const _: () = {
    let foo = Fields {
        foo: 10,
        bar: None,
        baz: Ordering::Less,
        qux: "hello",
    };
     
    let bar = Fields {
        foo: 99,
        bar: Some(true),
        baz: Ordering::Greater,
        qux: "world",
    };
     
    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));
};