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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::convert::From;
use std::fmt;
use std::ops::Deref;
#[repr(transparent)]
#[derive(Default)]
pub struct UniqueSortedVec<T>(Vec<T>);
impl<T> UniqueSortedVec<T> {
#[inline]
pub const fn new() -> Self {
Self(Vec::new())
}
}
impl<T: Ord> UniqueSortedVec<T> {
#[inline]
pub fn to_ref<U: Ord + ?Sized>(&self) -> UniqueSortedVec<&U>
where
T: Borrow<U>,
{
UniqueSortedVec(self.0.iter().map(Borrow::borrow).collect())
}
#[inline]
pub fn union(mut self, mut other: Self) -> Self {
match (self.as_slice(), other.as_slice()) {
(_, []) => self,
([], _) => other,
([.., tail_x], [.., tail_y]) => {
let last = match tail_x.cmp(tail_y) {
Ordering::Greater => self.0.pop().unwrap(),
Ordering::Less => other.0.pop().unwrap(),
Ordering::Equal => {
other.0.pop().unwrap();
self.0.pop().unwrap()
}
};
let mut new_head = self.union(other);
new_head.0.push(last);
new_head
}
}
}
#[inline]
pub fn contains(&self, x: &T) -> bool {
self.0.binary_search(x).is_ok()
}
#[inline]
pub fn find_first_following(&self, x: &T) -> Option<&T> {
match self.0.binary_search(x) {
Ok(i) | Err(i) => self.0.get(i),
}
}
}
impl<T: Ord> From<Vec<T>> for UniqueSortedVec<T> {
#[inline]
fn from(mut vec: Vec<T>) -> Self {
vec.sort_unstable();
vec.dedup();
Self(vec)
}
}
impl<T: Ord> From<UniqueSortedVec<T>> for Vec<T> {
#[inline]
fn from(val: UniqueSortedVec<T>) -> Self {
val.0
}
}
impl<T: Ord + Clone> Clone for UniqueSortedVec<T> {
#[inline]
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<T: Ord + fmt::Debug> fmt::Debug for UniqueSortedVec<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "UniqueSortedVec({:?})", self.0)
}
}
impl<T: Ord> Deref for UniqueSortedVec<T> {
type Target = Vec<T>;
#[inline]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T: Ord + Eq> Eq for UniqueSortedVec<T> {}
impl<T: Ord + PartialEq> PartialEq for UniqueSortedVec<T> {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.0.eq(&other.0)
}
}