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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
//! A set based on a lock-free skip list. See [`SkipSet`].

use std::borrow::Borrow;
use std::fmt;
use std::iter::FromIterator;
use std::ops::Deref;
use std::ops::{Bound, RangeBounds};

use crate::map;

/// A set based on a lock-free skip list.
///
/// This is an alternative to [`BTreeSet`] which supports
/// concurrent access across multiple threads.
///
/// [`BTreeSet`]: std::collections::BTreeSet
pub struct SkipSet<T> {
    inner: map::SkipMap<T, ()>,
}

impl<T> SkipSet<T> {
    /// Returns a new, empty set.
    ///
    /// # Example
    ///
    /// ```
    /// use crossbeam_skiplist::SkipSet;
    ///
    /// let set: SkipSet<i32> = SkipSet::new();
    /// ```
    pub fn new() -> SkipSet<T> {
        SkipSet {
            inner: map::SkipMap::new(),
        }
    }

    /// Returns `true` if the set is empty.
    ///
    /// # Example
    ///
    /// ```
    /// use crossbeam_skiplist::SkipSet;
    ///
    /// let set = SkipSet::new();
    /// assert!(set.is_empty());
    ///
    /// set.insert(1);
    /// assert!(!set.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Returns the number of entries in the set.
    ///
    /// If the set is being concurrently modified, consider the returned number just an
    /// approximation without any guarantees.
    ///
    /// # Example
    ///
    /// ```
    /// use crossbeam_skiplist::SkipSet;
    ///
    /// let set = SkipSet::new();
    /// assert_eq!(set.len(), 0);
    ///
    /// set.insert(1);
    /// assert_eq!(set.len(), 1);
    /// ```
    pub fn len(&self) -> usize {
        self.inner.len()
    }
}

impl<T> SkipSet<T>
where
    T: Ord,
{
    /// Returns the entry with the smallest key.
    ///
    /// # Example
    ///
    /// ```
    /// use crossbeam_skiplist::SkipSet;
    ///
    /// let set = SkipSet::new();
    /// set.insert(1);
    /// assert_eq!(*set.front().unwrap(), 1);
    /// set.insert(2);
    /// assert_eq!(*set.front().unwrap(), 1);
    /// ```
    pub fn front(&self) -> Option<Entry<'_, T>> {
        self.inner.front().map(Entry::new)
    }

    /// Returns the entry with the largest key.
    ///
    /// # Example
    ///
    /// ```
    /// use crossbeam_skiplist::SkipSet;
    ///
    /// let set = SkipSet::new();
    /// set.insert(1);
    /// assert_eq!(*set.back().unwrap(), 1);
    /// set.insert(2);
    /// assert_eq!(*set.back().unwrap(), 2);
    /// ```
    pub fn back(&self) -> Option<Entry<'_, T>> {
        self.inner.back().map(Entry::new)
    }

    /// Returns `true` if the set contains a value for the specified key.
    ///
    /// # Example
    ///
    /// ```
    /// use crossbeam_skiplist::SkipSet;
    ///
    /// let set: SkipSet<_> = (1..=3).collect();
    /// assert!(set.contains(&1));
    /// assert!(!set.contains(&4));
    /// ```
    pub fn contains<Q>(&self, key: &Q) -> bool
    where
        T: Borrow<Q>,
        Q: Ord + ?Sized,
    {
        self.inner.contains_key(key)
    }

    /// Returns an entry with the specified `key`.
    ///
    /// # Example
    ///
    /// ```
    /// use crossbeam_skiplist::SkipSet;
    ///
    /// let set: SkipSet<_> = (1..=3).collect();
    /// assert_eq!(*set.get(&3).unwrap(), 3);
    /// assert!(set.get(&4).is_none());
    /// ```
    pub fn get<Q>(&self, key: &Q) -> Option<Entry<'_, T>>
    where
        T: Borrow<Q>,
        Q: Ord + ?Sized,
    {
        self.inner.get(key).map(Entry::new)
    }

    /// Returns an `Entry` pointing to the lowest element whose key is above
    /// the given bound. If no such element is found then `None` is
    /// returned.
    ///
    /// # Example
    ///
    /// ```
    /// use crossbeam_skiplist::SkipSet;
    /// use std::ops::Bound::*;
    ///
    /// let set = SkipSet::new();
    /// set.insert(6);
    /// set.insert(7);
    /// set.insert(12);
    ///
    /// let greater_than_five = set.lower_bound(Excluded(&5)).unwrap();
    /// assert_eq!(*greater_than_five, 6);
    ///
    /// let greater_than_six = set.lower_bound(Excluded(&6)).unwrap();
    /// assert_eq!(*greater_than_six, 7);
    ///
    /// let greater_than_thirteen = set.lower_bound(Excluded(&13));
    /// assert!(greater_than_thirteen.is_none());
    /// ```
    pub fn lower_bound<'a, Q>(&'a self, bound: Bound<&Q>) -> Option<Entry<'a, T>>
    where
        T: Borrow<Q>,
        Q: Ord + ?Sized,
    {
        self.inner.lower_bound(bound).map(Entry::new)
    }

    /// Returns an `Entry` pointing to the highest element whose key is below
    /// the given bound. If no such element is found then `None` is
    /// returned.
    ///
    /// # Example
    ///
    /// ```
    /// use crossbeam_skiplist::SkipSet;
    /// use std::ops::Bound::*;
    ///
    /// let set = SkipSet::new();
    /// set.insert(6);
    /// set.insert(7);
    /// set.insert(12);
    ///
    /// let less_than_eight = set.upper_bound(Excluded(&8)).unwrap();
    /// assert_eq!(*less_than_eight, 7);
    ///
    /// let less_than_six = set.upper_bound(Excluded(&6));
    /// assert!(less_than_six.is_none());
    /// ```
    pub fn upper_bound<'a, Q>(&'a self, bound: Bound<&Q>) -> Option<Entry<'a, T>>
    where
        T: Borrow<Q>,
        Q: Ord + ?Sized,
    {
        self.inner.upper_bound(bound).map(Entry::new)
    }

    /// Finds an entry with the specified key, or inserts a new `key`-`value` pair if none exist.
    ///
    /// # Example
    ///
    /// ```
    /// use crossbeam_skiplist::SkipSet;
    ///
    /// let set = SkipSet::new();
    /// let entry = set.get_or_insert(2);
    /// assert_eq!(*entry, 2);
    /// ```
    pub fn get_or_insert(&self, key: T) -> Entry<'_, T> {
        Entry::new(self.inner.get_or_insert(key, ()))
    }

    /// Returns an iterator over all entries in the set.
    ///
    /// # Examples
    ///
    /// ```
    /// use crossbeam_skiplist::SkipSet;
    ///
    /// let set = SkipSet::new();
    /// set.insert(6);
    /// set.insert(7);
    /// set.insert(12);
    ///
    /// let mut set_iter = set.iter();
    /// assert_eq!(*set_iter.next().unwrap(), 6);
    /// assert_eq!(*set_iter.next().unwrap(), 7);
    /// assert_eq!(*set_iter.next().unwrap(), 12);
    /// assert!(set_iter.next().is_none());
    /// ```
    pub fn iter(&self) -> Iter<'_, T> {
        Iter {
            inner: self.inner.iter(),
        }
    }

    /// Returns an iterator over a subset of entries in the set.
    ///
    /// # Example
    ///
    /// ```
    /// use crossbeam_skiplist::SkipSet;
    ///
    /// let set = SkipSet::new();
    /// set.insert(6);
    /// set.insert(7);
    /// set.insert(12);
    ///
    /// let mut set_range = set.range(5..=8);
    /// assert_eq!(*set_range.next().unwrap(), 6);
    /// assert_eq!(*set_range.next().unwrap(), 7);
    /// assert!(set_range.next().is_none());
    /// ```
    pub fn range<Q, R>(&self, range: R) -> Range<'_, Q, R, T>
    where
        T: Borrow<Q>,
        R: RangeBounds<Q>,
        Q: Ord + ?Sized,
    {
        Range {
            inner: self.inner.range(range),
        }
    }
}

impl<T> SkipSet<T>
where
    T: Ord + Send + 'static,
{
    /// Inserts a `key`-`value` pair into the set and returns the new entry.
    ///
    /// If there is an existing entry with this key, it will be removed before inserting the new
    /// one.
    ///
    /// # Example
    ///
    /// ```
    /// use crossbeam_skiplist::SkipSet;
    ///
    /// let set = SkipSet::new();
    /// set.insert(2);
    /// assert_eq!(*set.get(&2).unwrap(), 2);
    /// ```
    pub fn insert(&self, key: T) -> Entry<'_, T> {
        Entry::new(self.inner.insert(key, ()))
    }

    /// Removes an entry with the specified key from the set and returns it.
    ///
    /// The value will not actually be dropped until all references to it have gone
    /// out of scope.
    ///
    /// # Example
    ///
    /// ```
    /// use crossbeam_skiplist::SkipSet;
    ///
    /// let set = SkipSet::new();
    /// set.insert(2);
    /// assert_eq!(*set.remove(&2).unwrap(), 2);
    /// assert!(set.remove(&2).is_none());
    /// ```
    pub fn remove<Q>(&self, key: &Q) -> Option<Entry<'_, T>>
    where
        T: Borrow<Q>,
        Q: Ord + ?Sized,
    {
        self.inner.remove(key).map(Entry::new)
    }

    /// Removes an entry from the front of the set.
    /// Returns the removed entry.
    ///
    /// The value will not actually be dropped until all references to it have gone
    /// out of scope.
    ///
    /// # Example
    ///
    /// ```
    /// use crossbeam_skiplist::SkipSet;
    ///
    /// let set = SkipSet::new();
    /// set.insert(1);
    /// set.insert(2);
    ///
    /// assert_eq!(*set.pop_front().unwrap(), 1);
    /// assert_eq!(*set.pop_front().unwrap(), 2);
    ///
    /// // All entries have been removed now.
    /// assert!(set.is_empty());
    /// ```
    pub fn pop_front(&self) -> Option<Entry<'_, T>> {
        self.inner.pop_front().map(Entry::new)
    }

    /// Removes an entry from the back of the set.
    /// Returns the removed entry.
    ///
    /// The value will not actually be dropped until all references to it have gone
    /// out of scope.
    ///
    /// # Example
    ///
    /// ```
    /// use crossbeam_skiplist::SkipSet;
    ///
    /// let set = SkipSet::new();
    /// set.insert(1);
    /// set.insert(2);
    ///
    /// assert_eq!(*set.pop_back().unwrap(), 2);
    /// assert_eq!(*set.pop_back().unwrap(), 1);
    ///
    /// // All entries have been removed now.
    /// assert!(set.is_empty());
    /// ```
    pub fn pop_back(&self) -> Option<Entry<'_, T>> {
        self.inner.pop_back().map(Entry::new)
    }

    /// Iterates over the set and removes every entry.
    ///
    /// # Example
    ///
    /// ```
    /// use crossbeam_skiplist::SkipSet;
    ///
    /// let set = SkipSet::new();
    /// set.insert(1);
    /// set.insert(2);
    ///
    /// set.clear();
    /// assert!(set.is_empty());
    /// ```
    pub fn clear(&self) {
        self.inner.clear();
    }
}

impl<T> Default for SkipSet<T> {
    fn default() -> SkipSet<T> {
        SkipSet::new()
    }
}

impl<T> fmt::Debug for SkipSet<T>
where
    T: Ord + fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.pad("SkipSet { .. }")
    }
}

impl<T> IntoIterator for SkipSet<T> {
    type Item = T;
    type IntoIter = IntoIter<T>;

    fn into_iter(self) -> IntoIter<T> {
        IntoIter {
            inner: self.inner.into_iter(),
        }
    }
}

impl<'a, T> IntoIterator for &'a SkipSet<T>
where
    T: Ord,
{
    type Item = Entry<'a, T>;
    type IntoIter = Iter<'a, T>;

    fn into_iter(self) -> Iter<'a, T> {
        self.iter()
    }
}

impl<T> FromIterator<T> for SkipSet<T>
where
    T: Ord,
{
    fn from_iter<I>(iter: I) -> SkipSet<T>
    where
        I: IntoIterator<Item = T>,
    {
        let s = SkipSet::new();
        for t in iter {
            s.get_or_insert(t);
        }
        s
    }
}

/// A reference-counted entry in a set.
pub struct Entry<'a, T> {
    inner: map::Entry<'a, T, ()>,
}

impl<'a, T> Entry<'a, T> {
    fn new(inner: map::Entry<'a, T, ()>) -> Entry<'a, T> {
        Entry { inner }
    }

    /// Returns a reference to the value.
    pub fn value(&self) -> &T {
        self.inner.key()
    }

    /// Returns `true` if the entry is removed from the set.
    pub fn is_removed(&self) -> bool {
        self.inner.is_removed()
    }
}

impl<'a, T> Entry<'a, T>
where
    T: Ord,
{
    /// Moves to the next entry in the set.
    pub fn move_next(&mut self) -> bool {
        self.inner.move_next()
    }

    /// Moves to the previous entry in the set.
    pub fn move_prev(&mut self) -> bool {
        self.inner.move_prev()
    }

    /// Returns the next entry in the set.
    pub fn next(&self) -> Option<Entry<'a, T>> {
        self.inner.next().map(Entry::new)
    }

    /// Returns the previous entry in the set.
    pub fn prev(&self) -> Option<Entry<'a, T>> {
        self.inner.prev().map(Entry::new)
    }
}

impl<T> Entry<'_, T>
where
    T: Ord + Send + 'static,
{
    /// Removes the entry from the set.
    ///
    /// Returns `true` if this call removed the entry and `false` if it was already removed.
    pub fn remove(&self) -> bool {
        self.inner.remove()
    }
}

impl<'a, T> Clone for Entry<'a, T> {
    fn clone(&self) -> Entry<'a, T> {
        Entry {
            inner: self.inner.clone(),
        }
    }
}

impl<T> fmt::Debug for Entry<'_, T>
where
    T: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Entry")
            .field("value", self.value())
            .finish()
    }
}

impl<T> Deref for Entry<'_, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.value()
    }
}

/// An owning iterator over the entries of a `SkipSet`.
pub struct IntoIter<T> {
    inner: map::IntoIter<T, ()>,
}

impl<T> Iterator for IntoIter<T> {
    type Item = T;

    fn next(&mut self) -> Option<T> {
        self.inner.next().map(|(k, ())| k)
    }
}

impl<T> fmt::Debug for IntoIter<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.pad("IntoIter { .. }")
    }
}

/// An iterator over the entries of a `SkipSet`.
pub struct Iter<'a, T> {
    inner: map::Iter<'a, T, ()>,
}

impl<'a, T> Iterator for Iter<'a, T>
where
    T: Ord,
{
    type Item = Entry<'a, T>;

    fn next(&mut self) -> Option<Entry<'a, T>> {
        self.inner.next().map(Entry::new)
    }
}

impl<'a, T> DoubleEndedIterator for Iter<'a, T>
where
    T: Ord,
{
    fn next_back(&mut self) -> Option<Entry<'a, T>> {
        self.inner.next_back().map(Entry::new)
    }
}

impl<T> fmt::Debug for Iter<'_, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.pad("Iter { .. }")
    }
}

/// An iterator over a subset of entries of a `SkipSet`.
pub struct Range<'a, Q, R, T>
where
    T: Ord + Borrow<Q>,
    R: RangeBounds<Q>,
    Q: Ord + ?Sized,
{
    inner: map::Range<'a, Q, R, T, ()>,
}

impl<'a, Q, R, T> Iterator for Range<'a, Q, R, T>
where
    T: Ord + Borrow<Q>,
    R: RangeBounds<Q>,
    Q: Ord + ?Sized,
{
    type Item = Entry<'a, T>;

    fn next(&mut self) -> Option<Entry<'a, T>> {
        self.inner.next().map(Entry::new)
    }
}

impl<'a, Q, R, T> DoubleEndedIterator for Range<'a, Q, R, T>
where
    T: Ord + Borrow<Q>,
    R: RangeBounds<Q>,
    Q: Ord + ?Sized,
{
    fn next_back(&mut self) -> Option<Entry<'a, T>> {
        self.inner.next_back().map(Entry::new)
    }
}

impl<Q, R, T> fmt::Debug for Range<'_, Q, R, T>
where
    T: Ord + Borrow<Q> + fmt::Debug,
    R: RangeBounds<Q> + fmt::Debug,
    Q: Ord + ?Sized,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Range")
            .field("range", &self.inner.inner.range)
            .field("head", &self.inner.inner.head.as_ref().map(|e| e.key()))
            .field("tail", &self.inner.inner.tail.as_ref().map(|e| e.key()))
            .finish()
    }
}