mheap 0.1.1

Flexible binary heaps
Documentation
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
use std::{
    fmt,
    marker::PhantomData,
    mem::{self, ManuallyDrop},
    ptr,
};

use crate::Position;

type RawIdx = usize;

/// An opaque handle to an element of type `T`.
///
/// This is returned by [`IndexableHeap::push`] and can be used to access
/// the element later via [`IndexableHeap::by_index_mut`], even after
/// the heap has been reordered by other operations.
///
/// The index is opaque and should not be inspected directly. It's designed
/// to be used only with the heap that created it.
///
/// If the element is removed from the heap, the index becomes invalid.
/// Even when the element is then pushed back, the index might be different.
///
/// When indexing with an invalid index, the heap might, might not panic.
/// Since the heap reuses indices, indexing with stale index might just return some unrelated element.
///
/// # Examples
///
/// ```
/// use mheap::{IndexableHeap, MaxHeap};
///
/// let mut heap = IndexableHeap::<i32, MaxHeap>::new();
/// let idx = heap.push(42);
/// heap.push(10);
/// heap.push(100);
///
/// // Later, we can still access the element by its index
/// *heap.by_index_mut(idx) = 50;
/// assert_eq!(heap.pop(), Some(100)); // 100 is still the max
/// assert_eq!(heap.pop(), Some(50)); // Our modified element
/// assert_eq!(heap.pop(), Some(10));
/// ```
///
/// See [`IndexableHeap`] for details
///
/// [`IndexableHeap`]: crate::IndexableHeap
/// [`IndexableHeap::push`]: crate::IndexableHeap::push
/// [`IndexableHeap::by_index_mut`]: crate::IndexableHeap::by_index_mut
pub struct Idx<T>(RawIdx, PhantomData<T>);

impl<T> Idx<T> {
    fn new(index: RawIdx) -> Self {
        Self(index, PhantomData)
    }

    fn index(&self) -> usize {
        self.0
    }
}

impl<T> Clone for Idx<T> {
    fn clone(&self) -> Self {
        Self(self.0, PhantomData)
    }
}

impl<T> Copy for Idx<T> {}

impl<T> PartialEq for Idx<T> {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl<T> Eq for Idx<T> {}

impl<T> fmt::Debug for Idx<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Idx<{}>({})", std::any::type_name::<T>(), self.0)
    }
}

#[derive(Clone)]
pub(crate) struct IndexableVec<T> {
    data: Vec<(T, Idx<T>)>,
    position: SkipList,
}

impl<T> Default for IndexableVec<T> {
    fn default() -> Self {
        Self { data: Default::default(), position: Default::default() }
    }
}

impl<T> IndexableVec<T> {
    pub(crate) const fn new() -> Self {
        Self {
            data: Vec::new(),
            position: SkipList::new(),
        }
    }

    pub(crate) fn with_capacity(capacity: usize) -> Self {
        Self {
            data: Vec::with_capacity(capacity),
            position: SkipList::with_capacity(capacity),
        }
    }

    pub(crate) const fn len(&self) -> usize {
        self.data.len()
    }

    pub(crate) const fn capacity(&self) -> usize {
        self.data.capacity()
    }

    pub(crate) const fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    pub(crate) fn get(&self, pos: Position) -> &T {
        &self.data[pos].0
    }

    pub(crate) fn get_mut(&mut self, pos: Position) -> &mut T {
        &mut self.data[pos].0
    }

    pub(crate) fn push(&mut self, item: T) -> Idx<T> {
        let pos = self.data.len();
        let index = Idx::new(self.position.add(pos));
        self.data.push((item, index));
        index
    }

    pub(crate) fn pop(&mut self) -> Option<T> {
        let (item, index) = self.data.pop()?;
        // SAFETY: structure invariant
        unsafe { self.assert_index(self.data.len(), index) };
        self.position.remove(index.index());
        Some(item)
    }

    pub(crate) fn swap_remove(&mut self, pos: Position) -> T {
        let (item, index) = self.data.swap_remove(pos);
        // SAFETY: structure invariant
        unsafe { self.assert_index(pos, index) };
        self.position.remove(index.index());
        item
    }

    pub(crate) fn reserve(&mut self, additional: usize) {
        self.data.reserve(additional);
        self.position.reserve(additional);
    }

    pub(crate) fn reserve_exact(&mut self, additional: usize) {
        self.data.reserve_exact(additional);
        self.position.reserve_exact(additional);
    }

    pub(crate) fn shrink_to_fit(&mut self) {
        self.data.shrink_to_fit();
        self.position.shrink_to_fit();
    }

    pub(crate) fn shrink_to(&mut self, min_capacity: usize) {
        self.data.shrink_to(min_capacity);
        self.position.shrink_to(min_capacity);
    }

    fn record_position(&mut self, pos: Position) {
        let index = self.pos_to_index(pos);
        self.position.set(index.index(), pos);
    }

    pub(crate) fn iter(&self) -> Iter<'_, T> {
        Iter { inner: self.data.iter() }
    }

    pub(crate) fn index_to_pos(&self, index: Idx<T>) -> Position {
        let pos = self.position.get(index.index());
        // SAFETY: position map contains only valid positions
        unsafe { self.assert_pos(index, pos) };
        pos
    }

    pub(crate) fn pos_to_index(&self, pos: Position) -> Idx<T> {
        let index = self.data[pos].1;
        // SAFETY: data contains only valid indices
        unsafe { self.assert_index(pos, index) };
        return index;
    }

    /// Must ensure index is valid
    unsafe fn assert_index(&self, pos: Position, index: Idx<T>) {
        if !self.position.is_valid(index.index()) {
            if cfg!(debug_assertions) {
                panic!("position {pos} contains invalid index {}", index.index());
            }
            unsafe {
                std::hint::unreachable_unchecked();
            }
        }
    }

    /// Must ensure pos is valid
    unsafe fn assert_pos(&self, index: Idx<T>, pos: Position) {
        if pos >= self.data.len() {
            if cfg!(debug_assertions) {
                panic!(
                    "index {} resolved to invalid position {pos}; data length is {}",
                    index.index(),
                    self.data.len()
                );
            }
            unsafe {
                std::hint::unreachable_unchecked();
            }
        }
    }
}

pub struct Iter<'a, T> {
    inner: std::slice::Iter<'a, (T, Idx<T>)>,
}

impl<'a, T> Iterator for Iter<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|it| &it.0)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.inner.next_back().map(|it| &it.0)
    }
}

impl<'a, T> ExactSizeIterator for Iter<'a, T> { }
impl<'a, T> std::iter::FusedIterator for Iter<'a, T> { }

unsafe impl<T> crate::storage::Storage for IndexableVec<T> {
    fn len(&self) -> usize {
        self.data.len()
    }

    type Item = T;

    type Key = T;

    fn key(item: &Self::Item) -> &Self::Key {
        item
    }

    fn get(&self, pos: Position) -> &Self::Item {
        self.get(pos)
    }

    fn get_mut(&mut self, pos: Position) -> &mut Self::Item {
        self.get_mut(pos)
    }

    type Slot = (T, Idx<T>);

    fn slot_key(item: &Self::Slot) -> &Self::Key {
        &item.0
    }

    unsafe fn load(&self, pos: Position) -> ManuallyDrop<Self::Slot> {
        ManuallyDrop::new(unsafe { ptr::read(&self.data[pos]) })
    }

    unsafe fn store(&mut self, pos: Position, item: &mut ManuallyDrop<Self::Slot>) {
        unsafe { ptr::write(&mut self.data[pos], ManuallyDrop::take(item)) };
        self.record_position(pos);
    }

    unsafe fn move_element(&mut self, src: Position, dst: Position) {
        unsafe { ptr::copy_nonoverlapping(&self.data[src], &mut self.data[dst], 1) };
        self.record_position(dst);
    }
}

#[derive(Clone, Default)]
struct SkipList {
    data: Vec<SkipEntry>,
    first_skip: NextSkip,
}

#[derive(Clone)]
struct SkipEntry(usize);
#[derive(Clone, Copy)]
struct NextSkip(usize);

impl Default for NextSkip {
    fn default() -> Self {
        Self::NONE
    }
}

enum SkipEntryRepr {
    Data(Position),
    Skip { next_idx: NextSkip },
}

impl NextSkip {
    const NONE: Self = Self(0);

    fn some(next_idx: usize) -> Self {
        Self(next_idx + 1)
    }

    fn get(&self) -> Option<usize> {
        self.0.checked_sub(1)
    }
}

impl SkipEntry {
    const SKIP_BIT: usize = isize::MIN as usize;

    fn from_pos(pos: Position) -> Option<Self> {
        if pos & Self::SKIP_BIT == 0 {
            Some(Self(pos))
        } else {
            None
        }
    }

    fn from_skip(next_idx: NextSkip) -> Self {
        Self(next_idx.0 | Self::SKIP_BIT)
    }

    fn repr(&self) -> SkipEntryRepr {
        if self.0 & Self::SKIP_BIT == 0 {
            SkipEntryRepr::Data(self.0)
        } else {
            SkipEntryRepr::Skip {
                next_idx: NextSkip(self.0 & !Self::SKIP_BIT),
            }
        }
    }

    fn expect_skip(&self) -> NextSkip {
        return match self.repr() {
            SkipEntryRepr::Skip { next_idx } => next_idx,
            SkipEntryRepr::Data(_) => handle_data(),
        };

        #[cold]
        #[inline(never)]
        fn handle_data() -> ! {
            panic!("expected skip");
        }
    }

    fn is_data(&self) -> bool {
        matches!(self.repr(), SkipEntryRepr::Data(_))
    }

    fn expect_data(&self) -> Position {
        return match self.repr() {
            SkipEntryRepr::Data(data) => data,
            SkipEntryRepr::Skip { .. } => handle_skip(),
        };

        #[cold]
        #[inline(never)]
        fn handle_skip() -> ! {
            panic!("expected data");
        }
    }
}

impl SkipList {
    const fn new() -> Self {
        Self {
            data: Vec::new(),
            first_skip: NextSkip::NONE,
        }
    }

    fn with_capacity(capacity: usize) -> Self {
        Self {
            data: Vec::with_capacity(capacity),
            first_skip: NextSkip::NONE,
        }
    }

    fn reserve(&mut self, additional: usize) {
        self.data.reserve(additional);
    }

    fn reserve_exact(&mut self, additional: usize) {
        self.data.reserve_exact(additional);
    }

    fn shrink_to_fit(&mut self) {
        self.data.shrink_to_fit();
    }

    fn shrink_to(&mut self, min_capacity: usize) {
        self.data.shrink_to(min_capacity);
    }

    fn add(&mut self, pos: Position) -> RawIdx {
        let pos = SkipEntry::from_pos(pos).unwrap();
        if let Some(index) = self.first_skip.get() {
            // SAFETY: all skip entries must always be valid
            unsafe { self.assert_index(index) };
            let entry = mem::replace(&mut self.data[index], pos);
            self.first_skip = entry.expect_skip();
            index
        } else {
            let index = self.data.len();
            self.data.push(pos);
            index
        }
    }

    fn is_valid(&self, index: RawIdx) -> bool {
        self.data.get(index).is_some_and(|it| it.is_data())
    }

    fn get(&self, index: RawIdx) -> Position {
        self.data[index].expect_data()
    }

    fn set(&mut self, index: RawIdx, pos: Position) {
        self.data[index].expect_data();
        self.data[index] = SkipEntry::from_pos(pos).unwrap();
    }

    fn remove(&mut self, index: RawIdx) -> Position {
        if index == self.data.len() - 1 {
            // We do not need to touch `self.first_skip`, since it cannot point to the last element (it is data, not skip)
            self.data.pop().unwrap().expect_data()
        } else {
            let new_skip = SkipEntry::from_skip(self.first_skip);
            let pos = mem::replace(&mut self.data[index], new_skip).expect_data();
            self.first_skip = NextSkip::some(index);
            pos
        }
    }

    /// Must ensure index is valid
    unsafe fn assert_index(&self, index: RawIdx) {
        if index >= self.data.len() {
            if cfg!(debug_assertions) {
                panic!("index {index} is out of bounds");
            }
            unsafe {
                std::hint::unreachable_unchecked();
            }
        }
    }
}