Skip to main content

intid_core/utils/
order.rs

1//! Implements [`OrderByInt`].
2
3use crate::{EquivalentId, IntegerId, IntegerIdContiguous, IntegerIdCounter};
4use core::cmp::Ordering;
5use core::hash::{Hash, Hasher};
6
7/// A wrapper around an [`IntegerId`] which implements [`Eq`], [`Ord`], and [`Hash`]
8/// based on the integer value.
9#[derive(Copy, Clone, Debug, Default)]
10pub struct OrderByInt<T: IntegerId>(pub T);
11impl<T: IntegerId> IntegerId for OrderByInt<T> {
12    impl_newtype_id_body!(for OrderByInt(T));
13}
14impl<T: IntegerIdContiguous> IntegerIdContiguous for OrderByInt<T> {}
15impl<T: IntegerIdCounter> IntegerIdCounter for OrderByInt<T> {
16    const START: Self = OrderByInt(T::START);
17    const START_INT: Self::Int = T::START_INT;
18}
19impl<T: IntegerId> Ord for OrderByInt<T> {
20    #[inline]
21    fn cmp(&self, other: &Self) -> Ordering {
22        self.0.to_int().cmp(&other.0.to_int())
23    }
24}
25impl<T: IntegerId> PartialOrd for OrderByInt<T> {
26    #[inline]
27    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
28        Some(self.cmp(other))
29    }
30}
31impl<T: IntegerId> Eq for OrderByInt<T> {}
32impl<T: IntegerId> PartialEq for OrderByInt<T> {
33    #[inline]
34    fn eq(&self, other: &Self) -> bool {
35        self.0.to_int() == other.0.to_int()
36    }
37}
38impl<T: IntegerId> PartialEq<T> for OrderByInt<T> {
39    #[inline]
40    fn eq(&self, other: &T) -> bool {
41        self.0 == *other
42    }
43}
44
45impl<T: IntegerId> PartialOrd<T> for OrderByInt<T> {
46    #[inline]
47    fn partial_cmp(&self, other: &T) -> Option<Ordering> {
48        Some(self.cmp(&OrderByInt(*other)))
49    }
50}
51impl<T: IntegerId> Hash for OrderByInt<T> {
52    #[inline]
53    fn hash<H: Hasher>(&self, state: &mut H) {
54        self.0.to_int().hash(state);
55    }
56}
57impl<T: IntegerId> EquivalentId<T> for OrderByInt<T> {
58    #[inline]
59    fn as_id(&self) -> T {
60        self.0
61    }
62}
63impl<T: IntegerId> EquivalentId<T> for &'_ OrderByInt<T> {
64    #[inline]
65    fn as_id(&self) -> T {
66        self.0
67    }
68}
69impl<T: IntegerId> From<T> for OrderByInt<T> {
70    #[inline]
71    fn from(value: T) -> Self {
72        OrderByInt(value)
73    }
74}
75impl<T: IntegerId> AsRef<T> for OrderByInt<T> {
76    #[inline]
77    fn as_ref(&self) -> &T {
78        &self.0
79    }
80}
81impl<T: IntegerId> AsMut<T> for OrderByInt<T> {
82    #[inline]
83    fn as_mut(&mut self) -> &mut T {
84        &mut self.0
85    }
86}
87/// NOTE: We cannot implement `Borrow`, because our `Hash + Eq` might be different.
88#[cfg(any())]
89impl<T> Borrow for OrderByInt<T> {}