Skip to main content

clt_database/skiplist/
map.rs

1//! An ordered map based on a lock-free skip list. See [`SkipMap`].
2
3use core::{
4    fmt,
5    mem::ManuallyDrop,
6    ops::{Bound, RangeBounds},
7    ptr,
8};
9
10use crossbeam_epoch as epoch;
11
12use super::{
13    base::{self, try_pin_loop, SkiplistAllocator},
14    comparator::{BasicComparator, Comparator},
15};
16use crate::alloc::{TryReserveError, TursoAllocator};
17
18/// An ordered map based on a lock-free skip list.
19///
20/// This is an alternative to [`BTreeMap`] which supports
21/// concurrent access across multiple threads.
22///
23/// A custom comparator may be provided, causing all keys
24/// to be ordered by the comparison function used instead
25/// of the standard `Ord` impl. See [`Comparator`].
26///
27/// [`BTreeMap`]: std::collections::BTreeMap
28/// [`Comparator`]: super::comparator::Comparator
29pub struct SkipMap<K, V, C = BasicComparator, A: SkiplistAllocator = TursoAllocator> {
30    inner: base::SkipList<K, V, C, A>,
31}
32
33impl<K, V> SkipMap<K, V> {
34    /// Returns a new, empty map with the default comparator.
35    ///
36    /// # Example
37    ///
38    /// ```
39    /// use turso_core::skiplist::SkipMap;
40    ///
41    /// let map: SkipMap<i32, &str> = SkipMap::new();
42    /// ```
43    pub fn new() -> Self {
44        Self {
45            inner: base::SkipList::new(epoch::default_collector().clone()),
46        }
47    }
48}
49
50impl<K, V, A: SkiplistAllocator> SkipMap<K, V, BasicComparator, A> {
51    /// Returns a new, empty map with the default comparator that allocates its
52    /// nodes in `alloc`.
53    ///
54    /// # Example
55    ///
56    /// ```
57    /// use turso_core::alloc::TursoAllocator;
58    /// use turso_core::skiplist::SkipMap;
59    ///
60    /// let map: SkipMap<i32, &str, _, TursoAllocator> = SkipMap::new_in(TursoAllocator);
61    /// ```
62    pub fn new_in(alloc: A) -> Self {
63        Self {
64            inner: base::SkipList::new_in(epoch::default_collector().clone(), alloc),
65        }
66    }
67}
68
69impl<K, V, C> SkipMap<K, V, C> {
70    /// Returns a new, empty map with the given comparator.
71    ///
72    /// # Example
73    ///
74    /// ```
75    /// use turso_core::skiplist::{SkipMap, comparator::BasicComparator};
76    ///
77    /// let map: SkipMap<i32, &str> = SkipMap::with_comparator(BasicComparator);
78    /// ```
79    pub fn with_comparator(comparator: C) -> Self {
80        Self {
81            inner: base::SkipList::with_comparator(epoch::default_collector().clone(), comparator),
82        }
83    }
84}
85
86impl<K, V, C, A: SkiplistAllocator> SkipMap<K, V, C, A> {
87    /// Returns a new, empty map with the given comparator that allocates its
88    /// nodes in `alloc`.
89    ///
90    /// # Example
91    ///
92    /// ```
93    /// use turso_core::alloc::TursoAllocator;
94    /// use turso_core::skiplist::{SkipMap, comparator::BasicComparator};
95    ///
96    /// let map: SkipMap<i32, &str, _, TursoAllocator> =
97    ///     SkipMap::with_comparator_in(BasicComparator, TursoAllocator);
98    /// ```
99    pub fn with_comparator_in(comparator: C, alloc: A) -> Self {
100        Self {
101            inner: base::SkipList::with_comparator_in(
102                epoch::default_collector().clone(),
103                comparator,
104                alloc,
105            ),
106        }
107    }
108
109    /// Returns `true` if the map is empty.
110    ///
111    /// # Example
112    /// ```
113    /// use turso_core::skiplist::SkipMap;
114    ///
115    /// let map: SkipMap<&str, &str> = SkipMap::new();
116    /// assert!(map.is_empty());
117    ///
118    /// map.insert("key", "value");
119    /// assert!(!map.is_empty());
120    /// ```
121    pub fn is_empty(&self) -> bool {
122        self.inner.is_empty()
123    }
124
125    /// Returns the number of entries in the map.
126    ///
127    /// If the map is being concurrently modified, consider the returned number just an
128    /// approximation without any guarantees.
129    ///
130    /// # Example
131    /// ```
132    /// use turso_core::skiplist::SkipMap;
133    ///
134    /// let map = SkipMap::new();
135    /// map.insert(0, 1);
136    /// assert_eq!(map.len(), 1);
137    ///
138    /// for x in 1..=5 {
139    ///     map.insert(x, x + 1);
140    /// }
141    ///
142    /// assert_eq!(map.len(), 6);
143    /// ```
144    pub fn len(&self) -> usize {
145        self.inner.len()
146    }
147}
148
149impl<K, V, C, A: SkiplistAllocator> SkipMap<K, V, C, A>
150where
151    C: Comparator<K>,
152{
153    /// Returns the entry with the smallest key.
154    ///
155    /// This function returns an [`Entry`] which
156    /// can be used to access the key's associated value.
157    ///
158    /// # Example
159    /// ```
160    /// use turso_core::skiplist::SkipMap;
161    ///
162    /// let numbers = SkipMap::new();
163    /// numbers.insert(5, "five");
164    /// assert_eq!(*numbers.front().unwrap().value(), "five");
165    /// numbers.insert(6, "six");
166    /// assert_eq!(*numbers.front().unwrap().value(), "five");
167    /// ```
168    pub fn front(&self) -> Option<Entry<'_, K, V, C, A>> {
169        let guard = &epoch::pin();
170        try_pin_loop(|| self.inner.front(guard)).map(Entry::new)
171    }
172
173    /// Returns the entry with the largest key.
174    ///
175    /// This function returns an [`Entry`] which
176    /// can be used to access the key's associated value.
177    ///
178    /// # Example
179    /// ```
180    /// use turso_core::skiplist::SkipMap;
181    ///
182    /// let numbers = SkipMap::new();
183    /// numbers.insert(5, "five");
184    /// assert_eq!(*numbers.back().unwrap().value(), "five");
185    /// numbers.insert(6, "six");
186    /// assert_eq!(*numbers.back().unwrap().value(), "six");
187    /// ```
188    pub fn back(&self) -> Option<Entry<'_, K, V, C, A>> {
189        let guard = &epoch::pin();
190        try_pin_loop(|| self.inner.back(guard)).map(Entry::new)
191    }
192
193    /// Finds an entry with the specified key, or inserts a new `key`-`value` pair if none exist.
194    ///
195    /// This function returns an [`Entry`] which
196    /// can be used to access the key's associated value.
197    ///
198    /// # Example
199    /// ```
200    /// use turso_core::skiplist::SkipMap;
201    ///
202    /// let ages = SkipMap::new();
203    /// let gates_age = ages.get_or_insert("Bill Gates", 64);
204    /// assert_eq!(*gates_age.value(), 64);
205    ///
206    /// ages.insert("Steve Jobs", 65);
207    /// let jobs_age = ages.get_or_insert("Steve Jobs", -1);
208    /// assert_eq!(*jobs_age.value(), 65);
209    /// ```
210    pub fn get_or_insert(&self, key: K, value: V) -> Entry<'_, K, V, C, A> {
211        let guard = &epoch::pin();
212        Entry::new(self.inner.get_or_insert(key, value, guard))
213    }
214
215    /// Fallible version of [`get_or_insert`](Self::get_or_insert): returns an error instead of
216    /// aborting the process when node allocation fails.
217    ///
218    /// On error the map is unchanged and both `key` and `value` are dropped.
219    ///
220    /// # Example
221    /// ```
222    /// use turso_core::skiplist::SkipMap;
223    ///
224    /// let ages = SkipMap::new();
225    /// let gates_age = ages.try_get_or_insert("Bill Gates", 64).unwrap();
226    /// assert_eq!(*gates_age.value(), 64);
227    /// ```
228    pub fn try_get_or_insert(
229        &self,
230        key: K,
231        value: V,
232    ) -> Result<Entry<'_, K, V, C, A>, TryReserveError> {
233        let guard = &epoch::pin();
234        self.inner
235            .try_get_or_insert(key, value, guard)
236            .map(Entry::new)
237    }
238
239    /// Finds an entry with the specified key, or inserts a new `key`-`value` pair if none exist,
240    /// where value is calculated with a function.
241    ///
242    /// <b>Note:</b> Another thread may write key value first, leading to the result of this closure
243    /// discarded. If closure is modifying some other state (such as shared counters or shared
244    /// objects), it may lead to <u>undesired behaviour</u> such as counters being changed without
245    /// result of closure inserted
246    ///
247    /// This function returns an [`Entry`] which
248    /// can be used to access the key's associated value.
249    ///
250    /// # Example
251    /// ```
252    /// use turso_core::skiplist::SkipMap;
253    ///
254    /// let ages = SkipMap::new();
255    /// let gates_age = ages.get_or_insert_with("Bill Gates", || 64);
256    /// assert_eq!(*gates_age.value(), 64);
257    ///
258    /// ages.insert("Steve Jobs", 65);
259    /// let jobs_age = ages.get_or_insert_with("Steve Jobs", || -1);
260    /// assert_eq!(*jobs_age.value(), 65);
261    /// ```
262    pub fn get_or_insert_with<F>(&self, key: K, value_fn: F) -> Entry<'_, K, V, C, A>
263    where
264        F: FnOnce() -> V,
265    {
266        let guard = &epoch::pin();
267        Entry::new(self.inner.get_or_insert_with(key, value_fn, guard))
268    }
269
270    /// Fallible version of [`get_or_insert_with`](Self::get_or_insert_with): returns an error
271    /// instead of aborting the process when node allocation fails.
272    ///
273    /// On error the map is unchanged and both `key` and the value built by `value_fn` are
274    /// dropped.
275    ///
276    /// # Example
277    /// ```
278    /// use turso_core::skiplist::SkipMap;
279    ///
280    /// let ages = SkipMap::new();
281    /// let gates_age = ages.try_get_or_insert_with("Bill Gates", || 64).unwrap();
282    /// assert_eq!(*gates_age.value(), 64);
283    /// ```
284    pub fn try_get_or_insert_with<F>(
285        &self,
286        key: K,
287        value_fn: F,
288    ) -> Result<Entry<'_, K, V, C, A>, TryReserveError>
289    where
290        F: FnOnce() -> V,
291    {
292        let guard = &epoch::pin();
293        self.inner
294            .try_get_or_insert_with(key, value_fn, guard)
295            .map(Entry::new)
296    }
297
298    /// Returns an iterator over all entries in the map,
299    /// sorted by key.
300    ///
301    /// This iterator returns [`Entry`]s which
302    /// can be used to access keys and their associated values.
303    ///
304    /// # Examples
305    /// ```
306    /// use turso_core::skiplist::SkipMap;
307    ///
308    /// let numbers = SkipMap::new();
309    /// numbers.insert(6, "six");
310    /// numbers.insert(7, "seven");
311    /// numbers.insert(12, "twelve");
312    ///
313    /// // Print then numbers from least to greatest
314    /// for entry in numbers.iter() {
315    ///     let number = entry.key();
316    ///     let number_str = entry.value();
317    ///     println!("{} is {}", number, number_str);
318    /// }
319    /// ```
320    pub fn iter(&self) -> Iter<'_, K, V, C, A> {
321        Iter {
322            inner: self.inner.ref_iter(),
323        }
324    }
325}
326
327impl<K, V, C, A: SkiplistAllocator> SkipMap<K, V, C, A>
328where
329    C: Comparator<K>,
330{
331    /// Returns `true` if the map contains a value for the specified key.
332    ///
333    /// # Example
334    /// ```
335    /// use turso_core::skiplist::SkipMap;
336    ///
337    /// let ages = SkipMap::new();
338    /// ages.insert("Bill Gates", 64);
339    ///
340    /// assert!(ages.contains_key(&"Bill Gates"));
341    /// assert!(!ages.contains_key(&"Steve Jobs"));
342    /// ```
343    pub fn contains_key<Q>(&self, key: &Q) -> bool
344    where
345        C: Comparator<K, Q>,
346        Q: ?Sized,
347    {
348        let guard = &epoch::pin();
349        self.inner.contains_key(key, guard)
350    }
351
352    /// Returns an entry with the specified `key`.
353    ///
354    /// This function returns an [`Entry`] which
355    /// can be used to access the key's associated value.
356    ///
357    /// # Example
358    /// ```
359    /// use turso_core::skiplist::SkipMap;
360    ///
361    /// let numbers: SkipMap<&str, i32> = SkipMap::new();
362    /// assert!(numbers.get("six").is_none());
363    ///
364    /// numbers.insert("six", 6);
365    /// assert_eq!(*numbers.get("six").unwrap().value(), 6);
366    /// ```
367    pub fn get<Q>(&self, key: &Q) -> Option<Entry<'_, K, V, C, A>>
368    where
369        C: Comparator<K, Q>,
370        Q: ?Sized,
371    {
372        let guard = &epoch::pin();
373        try_pin_loop(|| self.inner.get(key, guard)).map(Entry::new)
374    }
375
376    /// Returns an `Entry` pointing to the lowest element whose key is above
377    /// the given bound. If no such element is found then `None` is
378    /// returned.
379    ///
380    /// This function returns an [`Entry`] which
381    /// can be used to access the key's associated value.
382    ///
383    /// # Example
384    /// ```
385    /// use turso_core::skiplist::SkipMap;
386    /// use std::ops::Bound::*;
387    ///
388    /// let numbers = SkipMap::new();
389    /// numbers.insert(6, "six");
390    /// numbers.insert(7, "seven");
391    /// numbers.insert(12, "twelve");
392    ///
393    /// let greater_than_five = numbers.lower_bound(Excluded(&5)).unwrap();
394    /// assert_eq!(*greater_than_five.value(), "six");
395    ///
396    /// let greater_than_six = numbers.lower_bound(Excluded(&6)).unwrap();
397    /// assert_eq!(*greater_than_six.value(), "seven");
398    ///
399    /// let greater_than_thirteen = numbers.lower_bound(Excluded(&13));
400    /// assert!(greater_than_thirteen.is_none());
401    /// ```
402    pub fn lower_bound<'a, Q>(&'a self, bound: Bound<&Q>) -> Option<Entry<'a, K, V, C, A>>
403    where
404        C: Comparator<K, Q>,
405        Q: ?Sized,
406    {
407        let guard = &epoch::pin();
408        try_pin_loop(|| self.inner.lower_bound(bound, guard)).map(Entry::new)
409    }
410
411    /// Returns an `Entry` pointing to the highest element whose key is below
412    /// the given bound. If no such element is found then `None` is
413    /// returned.
414    ///
415    /// This function returns an [`Entry`] which
416    /// can be used to access the key's associated value.
417    ///
418    /// # Example
419    /// ```
420    /// use turso_core::skiplist::SkipMap;
421    /// use std::ops::Bound::*;
422    ///
423    /// let numbers = SkipMap::new();
424    /// numbers.insert(6, "six");
425    /// numbers.insert(7, "seven");
426    /// numbers.insert(12, "twelve");
427    ///
428    /// let less_than_eight = numbers.upper_bound(Excluded(&8)).unwrap();
429    /// assert_eq!(*less_than_eight.value(), "seven");
430    ///
431    /// let less_than_six = numbers.upper_bound(Excluded(&6));
432    /// assert!(less_than_six.is_none());
433    /// ```
434    pub fn upper_bound<'a, Q>(&'a self, bound: Bound<&Q>) -> Option<Entry<'a, K, V, C, A>>
435    where
436        C: Comparator<K, Q>,
437        Q: ?Sized,
438    {
439        let guard = &epoch::pin();
440        try_pin_loop(|| self.inner.upper_bound(bound, guard)).map(Entry::new)
441    }
442
443    /// Returns an iterator over a subset of entries in the map.
444    ///
445    /// This iterator returns [`Entry`]s which
446    /// can be used to access keys and their associated values.
447    ///
448    /// # Example
449    /// ```
450    /// use turso_core::skiplist::SkipMap;
451    ///
452    /// let numbers = SkipMap::new();
453    /// numbers.insert(6, "six");
454    /// numbers.insert(7, "seven");
455    /// numbers.insert(12, "twelve");
456    ///
457    /// // Print all numbers in the map between 5 and 8.
458    /// for entry in numbers.range(5..=8) {
459    ///     let number = entry.key();
460    ///     let number_str = entry.value();
461    ///     println!("{} is {}", number, number_str);
462    /// }
463    /// ```
464    pub fn range<Q, R>(&self, range: R) -> Range<'_, Q, R, K, V, C, A>
465    where
466        R: RangeBounds<Q>,
467        C: Comparator<K, Q>,
468        Q: ?Sized,
469    {
470        Range {
471            inner: self.inner.ref_range(range),
472        }
473    }
474}
475
476impl<K, V, C, A: SkiplistAllocator> SkipMap<K, V, C, A>
477where
478    C: Comparator<K>,
479    K: Send + 'static,
480    V: Send + 'static,
481{
482    /// Inserts a `key`-`value` pair into the map and returns the new entry.
483    ///
484    /// If there is an existing entry with this key, it will be removed before inserting the new
485    /// one.
486    ///
487    /// This function returns an [`Entry`] which
488    /// can be used to access the inserted key's associated value.
489    ///
490    /// # Example
491    /// ```
492    /// use turso_core::skiplist::SkipMap;
493    ///
494    /// let map = SkipMap::new();
495    /// map.insert("key", "value");
496    ///
497    /// assert_eq!(*map.get("key").unwrap().value(), "value");
498    /// ```
499    pub fn insert(&self, key: K, value: V) -> Entry<'_, K, V, C, A> {
500        let guard = &epoch::pin();
501        Entry::new(self.inner.insert(key, value, guard))
502    }
503
504    /// Fallible version of [`insert`](Self::insert): returns an error instead of aborting the
505    /// process when node allocation fails.
506    ///
507    /// On error the map is unchanged and both `key` and `value` are dropped.
508    ///
509    /// # Example
510    /// ```
511    /// use turso_core::skiplist::SkipMap;
512    ///
513    /// let map = SkipMap::new();
514    /// map.try_insert("key", "value").unwrap();
515    ///
516    /// assert_eq!(*map.get("key").unwrap().value(), "value");
517    /// ```
518    pub fn try_insert(&self, key: K, value: V) -> Result<Entry<'_, K, V, C, A>, TryReserveError> {
519        let guard = &epoch::pin();
520        self.inner.try_insert(key, value, guard).map(Entry::new)
521    }
522
523    /// Inserts a `key`-`value` pair into the skip list and returns the new entry.
524    ///
525    /// If there is an existing entry with this key and compare(entry.value) returns true,
526    /// it will be removed before inserting the new one.
527    /// The closure will not be called if the key is not present.
528    ///
529    /// This function returns an [`Entry`] which
530    /// can be used to access the inserted key's associated value.
531    ///
532    /// # Example
533    /// ```
534    /// use turso_core::skiplist::SkipMap;
535    ///
536    /// let map = SkipMap::new();
537    /// map.insert("key", 1);
538    /// map.compare_insert("key", 0, |x| x < &0);
539    /// assert_eq!(*map.get("key").unwrap().value(), 1);
540    /// map.compare_insert("key", 2, |x| x < &2);
541    /// assert_eq!(*map.get("key").unwrap().value(), 2);
542    /// map.compare_insert("absent_key", 0, |_| false);
543    /// assert_eq!(*map.get("absent_key").unwrap().value(), 0);
544    /// ```
545    pub fn compare_insert<F>(&self, key: K, value: V, compare_fn: F) -> Entry<'_, K, V, C, A>
546    where
547        F: Fn(&V) -> bool,
548    {
549        let guard = &epoch::pin();
550        Entry::new(self.inner.compare_insert(key, value, compare_fn, guard))
551    }
552
553    /// Fallible version of [`compare_insert`](Self::compare_insert): returns an error instead of
554    /// aborting the process when node allocation fails.
555    ///
556    /// On error the map is unchanged and both `key` and `value` are dropped.
557    ///
558    /// # Example
559    /// ```
560    /// use turso_core::skiplist::SkipMap;
561    ///
562    /// let map = SkipMap::new();
563    /// map.try_insert("key", 1).unwrap();
564    /// map.try_compare_insert("key", 2, |x| x < &2).unwrap();
565    /// assert_eq!(*map.get("key").unwrap().value(), 2);
566    /// ```
567    pub fn try_compare_insert<F>(
568        &self,
569        key: K,
570        value: V,
571        compare_fn: F,
572    ) -> Result<Entry<'_, K, V, C, A>, TryReserveError>
573    where
574        F: Fn(&V) -> bool,
575    {
576        let guard = &epoch::pin();
577        self.inner
578            .try_compare_insert(key, value, compare_fn, guard)
579            .map(Entry::new)
580    }
581
582    /// Removes an entry with the specified `key` from the map and returns it.
583    ///
584    /// The value will not actually be dropped until all references to it have gone
585    /// out of scope.
586    ///
587    /// This function returns an [`Entry`] which
588    /// can be used to access the removed key's associated value.
589    ///
590    /// # Example
591    /// ```
592    /// use turso_core::skiplist::SkipMap;
593    ///
594    /// let map: SkipMap<&str, &str> = SkipMap::new();
595    /// assert!(map.remove("invalid key").is_none());
596    ///
597    /// map.insert("key", "value");
598    /// assert_eq!(*map.remove("key").unwrap().value(), "value");
599    /// ```
600    pub fn remove<Q>(&self, key: &Q) -> Option<Entry<'_, K, V, C, A>>
601    where
602        C: Comparator<K, Q>,
603        Q: ?Sized,
604    {
605        let guard = &epoch::pin();
606        self.inner.remove(key, guard).map(Entry::new)
607    }
608
609    /// Removes the entry with the lowest key
610    /// from the map. Returns the removed entry.
611    ///
612    /// The value will not actually be dropped until all references to it have gone
613    /// out of scope.
614    ///
615    /// # Example
616    /// ```
617    /// use turso_core::skiplist::SkipMap;
618    ///
619    /// let numbers = SkipMap::new();
620    /// numbers.insert(6, "six");
621    /// numbers.insert(7, "seven");
622    /// numbers.insert(12, "twelve");
623    ///
624    /// assert_eq!(*numbers.pop_front().unwrap().value(), "six");
625    /// assert_eq!(*numbers.pop_front().unwrap().value(), "seven");
626    /// assert_eq!(*numbers.pop_front().unwrap().value(), "twelve");
627    ///
628    /// // All entries have been removed now.
629    /// assert!(numbers.is_empty());
630    /// ```
631    pub fn pop_front(&self) -> Option<Entry<'_, K, V, C, A>> {
632        let guard = &epoch::pin();
633        self.inner.pop_front(guard).map(Entry::new)
634    }
635
636    /// Removes the entry with the greatest key from the map.
637    /// Returns the removed entry.
638    ///
639    /// The value will not actually be dropped until all references to it have gone
640    /// out of scope.
641    ///
642    /// # Example
643    /// ```
644    /// use turso_core::skiplist::SkipMap;
645    ///
646    /// let numbers = SkipMap::new();
647    /// numbers.insert(6, "six");
648    /// numbers.insert(7, "seven");
649    /// numbers.insert(12, "twelve");
650    ///
651    /// assert_eq!(*numbers.pop_back().unwrap().value(), "twelve");
652    /// assert_eq!(*numbers.pop_back().unwrap().value(), "seven");
653    /// assert_eq!(*numbers.pop_back().unwrap().value(), "six");
654    ///
655    /// // All entries have been removed now.
656    /// assert!(numbers.is_empty());
657    /// ```
658    pub fn pop_back(&self) -> Option<Entry<'_, K, V, C, A>> {
659        let guard = &epoch::pin();
660        self.inner.pop_back(guard).map(Entry::new)
661    }
662
663    /// Removes all entries from the map.
664    ///
665    /// # Example
666    /// ```
667    /// use turso_core::skiplist::SkipMap;
668    ///
669    /// let people = SkipMap::new();
670    /// people.insert("Bill", "Gates");
671    /// people.insert("Steve", "Jobs");
672    ///
673    /// people.clear();
674    /// assert!(people.is_empty());
675    /// ```
676    pub fn clear(&self) {
677        let guard = &mut epoch::pin();
678        self.inner.clear(guard);
679    }
680}
681
682impl<K, V, C> Default for SkipMap<K, V, C>
683where
684    C: Default,
685{
686    fn default() -> Self {
687        Self::with_comparator(Default::default())
688    }
689}
690
691impl<K, V, C, A: SkiplistAllocator> fmt::Debug for SkipMap<K, V, C, A>
692where
693    K: fmt::Debug,
694    V: fmt::Debug,
695{
696    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
697        f.pad("SkipMap { .. }")
698    }
699}
700
701impl<K, V, C, A: SkiplistAllocator> IntoIterator for SkipMap<K, V, C, A> {
702    type Item = (K, V);
703    type IntoIter = IntoIter<K, V, A>;
704
705    fn into_iter(self) -> Self::IntoIter {
706        IntoIter {
707            inner: self.inner.into_iter(),
708        }
709    }
710}
711
712impl<'a, K, V, C, A: SkiplistAllocator> IntoIterator for &'a SkipMap<K, V, C, A>
713where
714    C: Comparator<K>,
715{
716    type Item = Entry<'a, K, V, C, A>;
717    type IntoIter = Iter<'a, K, V, C, A>;
718
719    fn into_iter(self) -> Self::IntoIter {
720        self.iter()
721    }
722}
723
724impl<K, V, C> FromIterator<(K, V)> for SkipMap<K, V, C>
725where
726    C: Comparator<K> + Default,
727{
728    fn from_iter<I>(iter: I) -> Self
729    where
730        I: IntoIterator<Item = (K, V)>,
731    {
732        let s = Self::default();
733        for (k, v) in iter {
734            s.get_or_insert(k, v);
735        }
736        s
737    }
738}
739
740/// A reference-counted entry in a map.
741pub struct Entry<'a, K, V, C = BasicComparator, A: SkiplistAllocator = TursoAllocator> {
742    inner: ManuallyDrop<base::RefEntry<'a, K, V, C, A>>,
743}
744
745impl<'a, K, V, C, A: SkiplistAllocator> Entry<'a, K, V, C, A> {
746    fn new(inner: base::RefEntry<'a, K, V, C, A>) -> Self {
747        Self {
748            inner: ManuallyDrop::new(inner),
749        }
750    }
751
752    /// Returns a reference to the key.
753    pub fn key(&self) -> &'a K {
754        self.inner.key()
755    }
756
757    /// Returns a reference to the value.
758    pub fn value(&self) -> &'a V {
759        self.inner.value()
760    }
761
762    /// Returns `true` if the entry is removed from the map.
763    pub fn is_removed(&self) -> bool {
764        self.inner.is_removed()
765    }
766}
767
768impl<K, V, C, A: SkiplistAllocator> Drop for Entry<'_, K, V, C, A> {
769    fn drop(&mut self) {
770        unsafe {
771            ManuallyDrop::into_inner(ptr::read(&self.inner)).release_with_pin(epoch::pin);
772        }
773    }
774}
775
776impl<K, V, C, A: SkiplistAllocator> Entry<'_, K, V, C, A>
777where
778    C: Comparator<K>,
779{
780    /// Moves to the next entry in the map.
781    pub fn move_next(&mut self) -> bool {
782        let guard = &epoch::pin();
783        self.inner.move_next(guard)
784    }
785
786    /// Moves to the previous entry in the map.
787    pub fn move_prev(&mut self) -> bool {
788        let guard = &epoch::pin();
789        self.inner.move_prev(guard)
790    }
791
792    /// Returns the next entry in the map.
793    pub fn next(&self) -> Option<Self> {
794        let guard = &epoch::pin();
795        self.inner.next(guard).map(Entry::new)
796    }
797
798    /// Returns the previous entry in the map.
799    pub fn prev(&self) -> Option<Self> {
800        let guard = &epoch::pin();
801        self.inner.prev(guard).map(Entry::new)
802    }
803}
804
805impl<K, V, C, A: SkiplistAllocator> Entry<'_, K, V, C, A>
806where
807    C: Comparator<K>,
808    K: Send + 'static,
809    V: Send + 'static,
810{
811    /// Removes the entry from the map.
812    ///
813    /// Returns `true` if this call removed the entry and `false` if it was already removed.
814    pub fn remove(&self) -> bool {
815        let guard = &epoch::pin();
816        self.inner.remove(guard)
817    }
818}
819
820impl<K, V, C, A: SkiplistAllocator> Clone for Entry<'_, K, V, C, A> {
821    fn clone(&self) -> Self {
822        Self {
823            inner: self.inner.clone(),
824        }
825    }
826}
827
828impl<K, V, C, A: SkiplistAllocator> fmt::Debug for Entry<'_, K, V, C, A>
829where
830    K: fmt::Debug,
831    V: fmt::Debug,
832{
833    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
834        f.debug_tuple("Entry")
835            .field(self.key())
836            .field(self.value())
837            .finish()
838    }
839}
840
841/// An owning iterator over the entries of a `SkipMap`.
842pub struct IntoIter<K, V, A: SkiplistAllocator = TursoAllocator> {
843    inner: base::IntoIter<K, V, A>,
844}
845
846impl<K, V, A: SkiplistAllocator> Iterator for IntoIter<K, V, A> {
847    type Item = (K, V);
848
849    fn next(&mut self) -> Option<Self::Item> {
850        self.inner.next()
851    }
852}
853
854impl<K, V, A: SkiplistAllocator> fmt::Debug for IntoIter<K, V, A> {
855    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
856        f.pad("IntoIter { .. }")
857    }
858}
859
860/// An iterator over the entries of a `SkipMap`.
861pub struct Iter<'a, K, V, C = BasicComparator, A: SkiplistAllocator = TursoAllocator> {
862    inner: base::RefIter<'a, K, V, C, A>,
863}
864
865impl<'a, K, V, C, A: SkiplistAllocator> Iterator for Iter<'a, K, V, C, A>
866where
867    C: Comparator<K>,
868{
869    type Item = Entry<'a, K, V, C, A>;
870
871    fn next(&mut self) -> Option<Entry<'a, K, V, C, A>> {
872        let guard = &epoch::pin();
873        self.inner.next(guard).map(Entry::new)
874    }
875}
876
877impl<'a, K, V, C, A: SkiplistAllocator> DoubleEndedIterator for Iter<'a, K, V, C, A>
878where
879    C: Comparator<K>,
880{
881    fn next_back(&mut self) -> Option<Entry<'a, K, V, C, A>> {
882        let guard = &epoch::pin();
883        self.inner.next_back(guard).map(Entry::new)
884    }
885}
886
887impl<K, V, C, A: SkiplistAllocator> fmt::Debug for Iter<'_, K, V, C, A> {
888    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
889        f.pad("Iter { .. }")
890    }
891}
892
893impl<K, V, C, A: SkiplistAllocator> Drop for Iter<'_, K, V, C, A> {
894    fn drop(&mut self) {
895        let guard = &epoch::pin();
896        self.inner.drop_impl(guard);
897    }
898}
899
900/// An iterator over a subset of entries of a `SkipMap`.
901pub struct Range<'a, Q, R, K, V, C = BasicComparator, A: SkiplistAllocator = TursoAllocator>
902where
903    C: Comparator<K> + Comparator<K, Q>,
904    R: RangeBounds<Q>,
905    Q: ?Sized,
906{
907    pub(crate) inner: base::RefRange<'a, Q, R, K, V, C, A>,
908}
909
910impl<'a, Q, R, K, V, C, A: SkiplistAllocator> Iterator for Range<'a, Q, R, K, V, C, A>
911where
912    C: Comparator<K> + Comparator<K, Q>,
913    R: RangeBounds<Q>,
914    Q: ?Sized,
915{
916    type Item = Entry<'a, K, V, C, A>;
917
918    fn next(&mut self) -> Option<Entry<'a, K, V, C, A>> {
919        let guard = &epoch::pin();
920        self.inner.next(guard).map(Entry::new)
921    }
922}
923
924impl<'a, Q, R, K, V, C, A: SkiplistAllocator> DoubleEndedIterator for Range<'a, Q, R, K, V, C, A>
925where
926    C: Comparator<K> + Comparator<K, Q>,
927    R: RangeBounds<Q>,
928    Q: ?Sized,
929{
930    fn next_back(&mut self) -> Option<Entry<'a, K, V, C, A>> {
931        let guard = &epoch::pin();
932        self.inner.next_back(guard).map(Entry::new)
933    }
934}
935
936impl<Q, R, K, V, C, A: SkiplistAllocator> fmt::Debug for Range<'_, Q, R, K, V, C, A>
937where
938    C: Comparator<K> + Comparator<K, Q>,
939    K: fmt::Debug,
940    V: fmt::Debug,
941    R: RangeBounds<Q> + fmt::Debug,
942    Q: ?Sized,
943{
944    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
945        f.debug_struct("Range")
946            .field("range", &self.inner.range)
947            .field("head", &self.inner.head)
948            .field("tail", &self.inner.tail)
949            .finish()
950    }
951}
952
953impl<Q, R, K, V, C, A: SkiplistAllocator> Drop for Range<'_, Q, R, K, V, C, A>
954where
955    C: Comparator<K> + Comparator<K, Q>,
956    R: RangeBounds<Q>,
957    Q: ?Sized,
958{
959    fn drop(&mut self) {
960        let guard = &epoch::pin();
961        self.inner.drop_impl(guard);
962    }
963}