1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
use std::cmp::PartialOrd;
use std::mem;
use std::ops::Deref;
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
#[cfg_attr(
feature = "rkyv",
derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)
)]
pub struct SortedPair<T: PartialOrd>([T; 2]);
impl<T: PartialOrd> SortedPair<T> {
pub fn new(element1: T, element2: T) -> Self {
if element1 > element2 {
SortedPair([element2, element1])
} else {
SortedPair([element1, element2])
}
}
}
impl<T: PartialOrd> Deref for SortedPair<T> {
type Target = (T, T);
fn deref(&self) -> &(T, T) {
unsafe { mem::transmute(self) }
}
}
#[cfg(feature = "rkyv")]
impl<T: rkyv::Archive + PartialOrd> std::hash::Hash for ArchivedSortedPair<T>
where
[<T as rkyv::Archive>::Archived; 2]: std::hash::Hash,
{
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.0.hash(state)
}
}
#[cfg(feature = "rkyv")]
impl<T: rkyv::Archive + PartialOrd> PartialEq for ArchivedSortedPair<T>
where
[<T as rkyv::Archive>::Archived; 2]: PartialEq,
{
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
#[cfg(feature = "rkyv")]
impl<T: rkyv::Archive + PartialOrd> Eq for ArchivedSortedPair<T> where
[<T as rkyv::Archive>::Archived; 2]: Eq
{
}