const_str/__ctfe/
compare.rs

1use core::cmp::Ordering;
2
3pub struct Compare<T1, T2>(pub T1, pub T2);
4
5impl Compare<&[u8], &[u8]> {
6    pub const fn const_eval(&self) -> Ordering {
7        crate::bytes::compare(self.0, self.1)
8    }
9}
10
11impl<const L1: usize, const L2: usize> Compare<&[u8; L1], &[u8; L2]> {
12    pub const fn const_eval(&self) -> Ordering {
13        crate::bytes::compare(self.0, self.1)
14    }
15}
16
17impl Compare<&str, &str> {
18    pub const fn const_eval(&self) -> Ordering {
19        crate::str::compare(self.0, self.1)
20    }
21}
22
23/// Compares two strings lexicographically.
24///
25/// This macro is [const-fn compatible](./index.html#const-fn-compatible).
26///
27/// See also [`equal!`](crate::equal).
28///
29/// # Examples
30///
31/// ```
32/// use core::cmp::Ordering;
33///
34/// const A: &str = "1";
35/// const B: &str = "10";
36/// const C: &str = "2";
37///
38/// const ORD: Ordering = const_str::compare!(A, B);
39/// assert_eq!(ORD, Ordering::Less);
40///
41/// assert!(const_str::compare!(<, A, B));
42/// assert!(const_str::compare!(<=, A, B));
43///
44/// assert!(const_str::compare!(>, C, A));
45/// assert!(const_str::compare!(>=, C, A));
46///
47/// assert!(const_str::compare!(==, A, A));
48/// ```
49///
50#[macro_export]
51macro_rules! compare {
52    (<, $lhs: expr, $rhs: expr) => {{
53        use ::core::cmp::Ordering;
54        let ordering = $crate::__ctfe::Compare($lhs, $rhs).const_eval();
55        matches!(ordering, Ordering::Less)
56    }};
57    (>, $lhs: expr, $rhs: expr) => {{
58        use ::core::cmp::Ordering;
59        let ordering = $crate::__ctfe::Compare($lhs, $rhs).const_eval();
60        matches!(ordering, Ordering::Greater)
61    }};
62    (==, $lhs: expr, $rhs: expr) => {{
63        use ::core::cmp::Ordering;
64        let ordering = $crate::__ctfe::Compare($lhs, $rhs).const_eval();
65        matches!(ordering, Ordering::Equal)
66    }};
67    (<=, $lhs: expr, $rhs: expr) => {{
68        use ::core::cmp::Ordering;
69        let ordering = $crate::__ctfe::Compare($lhs, $rhs).const_eval();
70        matches!(ordering, Ordering::Less | Ordering::Equal)
71    }};
72    (>=, $lhs: expr, $rhs: expr) => {{
73        use ::core::cmp::Ordering;
74        let ordering = $crate::__ctfe::Compare($lhs, $rhs).const_eval();
75        matches!(ordering, Ordering::Greater | Ordering::Equal)
76    }};
77    ($lhs: expr, $rhs: expr) => {
78        $crate::__ctfe::Compare($lhs, $rhs).const_eval()
79    };
80}