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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
use crate::stable_hasher::{HashStable, StableHasher};
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::iter::FromIterator;
use std::mem;
use std::ops::{Bound, Index, IndexMut, RangeBounds};
mod index_map;
pub use index_map::SortedIndexMultiMap;
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Encodable, Decodable)]
pub struct SortedMap<K, V> {
data: Vec<(K, V)>,
}
impl<K, V> Default for SortedMap<K, V> {
#[inline]
fn default() -> SortedMap<K, V> {
SortedMap { data: Vec::new() }
}
}
impl<K, V> SortedMap<K, V> {
#[inline]
pub const fn new() -> SortedMap<K, V> {
SortedMap { data: Vec::new() }
}
}
impl<K: Ord, V> SortedMap<K, V> {
#[inline]
pub fn from_presorted_elements(elements: Vec<(K, V)>) -> SortedMap<K, V> {
debug_assert!(elements.array_windows().all(|[fst, snd]| fst.0 < snd.0));
SortedMap { data: elements }
}
#[inline]
pub fn insert(&mut self, key: K, mut value: V) -> Option<V> {
match self.lookup_index_for(&key) {
Ok(index) => {
let slot = unsafe { self.data.get_unchecked_mut(index) };
mem::swap(&mut slot.1, &mut value);
Some(value)
}
Err(index) => {
self.data.insert(index, (key, value));
None
}
}
}
#[inline]
pub fn remove(&mut self, key: &K) -> Option<V> {
match self.lookup_index_for(key) {
Ok(index) => Some(self.data.remove(index).1),
Err(_) => None,
}
}
#[inline]
pub fn get<Q>(&self, key: &Q) -> Option<&V>
where
K: Borrow<Q>,
Q: Ord + ?Sized,
{
match self.lookup_index_for(key) {
Ok(index) => unsafe { Some(&self.data.get_unchecked(index).1) },
Err(_) => None,
}
}
#[inline]
pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
where
K: Borrow<Q>,
Q: Ord + ?Sized,
{
match self.lookup_index_for(key) {
Ok(index) => unsafe { Some(&mut self.data.get_unchecked_mut(index).1) },
Err(_) => None,
}
}
#[inline]
pub fn clear(&mut self) {
self.data.clear();
}
#[inline]
pub fn iter(&self) -> std::slice::Iter<'_, (K, V)> {
self.data.iter()
}
#[inline]
pub fn keys(&self) -> impl Iterator<Item = &K> + ExactSizeIterator + DoubleEndedIterator {
self.data.iter().map(|&(ref k, _)| k)
}
#[inline]
pub fn values(&self) -> impl Iterator<Item = &V> + ExactSizeIterator + DoubleEndedIterator {
self.data.iter().map(|&(_, ref v)| v)
}
#[inline]
pub fn len(&self) -> usize {
self.data.len()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
#[inline]
pub fn range<R>(&self, range: R) -> &[(K, V)]
where
R: RangeBounds<K>,
{
let (start, end) = self.range_slice_indices(range);
&self.data[start..end]
}
#[inline]
pub fn remove_range<R>(&mut self, range: R)
where
R: RangeBounds<K>,
{
let (start, end) = self.range_slice_indices(range);
self.data.splice(start..end, std::iter::empty());
}
#[inline]
pub fn offset_keys<F>(&mut self, f: F)
where
F: Fn(&mut K),
{
self.data.iter_mut().map(|&mut (ref mut k, _)| k).for_each(f);
}
#[inline]
pub fn insert_presorted(&mut self, elements: Vec<(K, V)>) {
if elements.is_empty() {
return;
}
debug_assert!(elements.array_windows().all(|[fst, snd]| fst.0 < snd.0));
let start_index = self.lookup_index_for(&elements[0].0);
let elements = match start_index {
Ok(index) => {
let mut elements = elements.into_iter();
self.data[index] = elements.next().unwrap();
elements
}
Err(index) => {
if index == self.data.len() || elements.last().unwrap().0 < self.data[index].0 {
self.data.splice(index..index, elements.into_iter());
return;
}
let mut elements = elements.into_iter();
self.data.insert(index, elements.next().unwrap());
elements
}
};
for (k, v) in elements {
self.insert(k, v);
}
}
#[inline(always)]
fn lookup_index_for<Q>(&self, key: &Q) -> Result<usize, usize>
where
K: Borrow<Q>,
Q: Ord + ?Sized,
{
self.data.binary_search_by(|&(ref x, _)| x.borrow().cmp(key))
}
#[inline]
fn range_slice_indices<R>(&self, range: R) -> (usize, usize)
where
R: RangeBounds<K>,
{
let start = match range.start_bound() {
Bound::Included(ref k) => match self.lookup_index_for(k) {
Ok(index) | Err(index) => index,
},
Bound::Excluded(ref k) => match self.lookup_index_for(k) {
Ok(index) => index + 1,
Err(index) => index,
},
Bound::Unbounded => 0,
};
let end = match range.end_bound() {
Bound::Included(ref k) => match self.lookup_index_for(k) {
Ok(index) => index + 1,
Err(index) => index,
},
Bound::Excluded(ref k) => match self.lookup_index_for(k) {
Ok(index) | Err(index) => index,
},
Bound::Unbounded => self.data.len(),
};
(start, end)
}
#[inline]
pub fn contains_key<Q>(&self, key: &Q) -> bool
where
K: Borrow<Q>,
Q: Ord + ?Sized,
{
self.get(key).is_some()
}
}
impl<K: Ord, V> IntoIterator for SortedMap<K, V> {
type Item = (K, V);
type IntoIter = std::vec::IntoIter<(K, V)>;
fn into_iter(self) -> Self::IntoIter {
self.data.into_iter()
}
}
impl<'a, K, Q, V> Index<&'a Q> for SortedMap<K, V>
where
K: Ord + Borrow<Q>,
Q: Ord + ?Sized,
{
type Output = V;
fn index(&self, key: &Q) -> &Self::Output {
self.get(key).expect("no entry found for key")
}
}
impl<'a, K, Q, V> IndexMut<&'a Q> for SortedMap<K, V>
where
K: Ord + Borrow<Q>,
Q: Ord + ?Sized,
{
fn index_mut(&mut self, key: &Q) -> &mut Self::Output {
self.get_mut(key).expect("no entry found for key")
}
}
impl<K: Ord, V> FromIterator<(K, V)> for SortedMap<K, V> {
fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
let mut data: Vec<(K, V)> = iter.into_iter().collect();
data.sort_unstable_by(|&(ref k1, _), &(ref k2, _)| k1.cmp(k2));
data.dedup_by(|&mut (ref k1, _), &mut (ref k2, _)| k1.cmp(k2) == Ordering::Equal);
SortedMap { data }
}
}
impl<K: HashStable<CTX>, V: HashStable<CTX>, CTX> HashStable<CTX> for SortedMap<K, V> {
#[inline]
fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
self.data.hash_stable(ctx, hasher);
}
}
#[cfg(test)]
mod tests;