1use std::{
2 cmp::Ordering,
3 ops::{Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive},
4};
5
6#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
7#[repr(transparent)]
8pub struct Lexicographic<T>(T);
9
10impl<T: LexicographicOrd> Ord for Lexicographic<T> {
11 #[inline]
12 fn cmp(&self, other: &Self) -> Ordering { self.0.lex_cmp(&other.0) }
13}
14
15impl<T: LexicographicOrd> PartialOrd for Lexicographic<T> {
16 #[inline]
17 fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) }
18}
19
20pub trait LexicographicOrd: Eq {
21 fn lex_cmp(&self, rhs: &Self) -> Ordering;
22}
23
24macro_rules! ord_impl {
25 () => {};
26
27 ($t:ty $(, $($tt:tt)*)?) => {
28 impl LexicographicOrd for $t {
29 #[inline]
30 fn lex_cmp(&self, rhs: &Self) -> Ordering { self.cmp(rhs) }
31 }
32
33 ord_impl!($($($tt)*)?);
34 };
35}
36
37ord_impl!(u8, u16, u32, u64, u128, i8, i16, i32, i64, i128, char);
38
39impl<T: Ord> LexicographicOrd for Range<T> {
40 fn lex_cmp(&self, rhs: &Self) -> Ordering {
41 let Self {
42 start: l_start,
43 end: l_end,
44 } = self;
45 let Self {
46 start: r_start,
47 end: r_end,
48 } = rhs;
49 l_start.cmp(r_start).then_with(|| l_end.cmp(r_end))
50 }
51}
52
53impl<T: Ord> LexicographicOrd for RangeFrom<T> {
54 fn lex_cmp(&self, rhs: &Self) -> Ordering {
55 let Self { start: l_start } = self;
56 let Self { start: r_start } = rhs;
57 l_start.cmp(r_start)
58 }
59}
60
61impl LexicographicOrd for RangeFull {
62 fn lex_cmp(&self, rhs: &Self) -> Ordering {
63 debug_assert_eq!(self, rhs);
64 Ordering::Equal
65 }
66}
67
68impl<T: Ord> LexicographicOrd for RangeInclusive<T> {
69 fn lex_cmp(&self, rhs: &Self) -> Ordering {
70 self.start()
71 .cmp(rhs.start())
72 .then_with(|| self.end().cmp(rhs.end()))
73 }
74}
75
76impl<T: Ord> LexicographicOrd for RangeTo<T> {
77 fn lex_cmp(&self, rhs: &Self) -> Ordering {
78 let Self { end: l_end } = self;
79 let Self { end: r_end } = rhs;
80 l_end.cmp(r_end)
81 }
82}
83
84impl<T: Ord> LexicographicOrd for RangeToInclusive<T> {
85 fn lex_cmp(&self, rhs: &Self) -> Ordering {
86 let Self { end: l_end } = self;
87 let Self { end: r_end } = rhs;
88 l_end.cmp(r_end)
89 }
90}