superset_map

B-tree-backed map whose keys are distinct supersets.
git clone https://git.philomathiclife.com/repos/superset_map
Log | Files | Refs | README

superset_map.rs (36991B)


      1 extern crate alloc;
      2 use crate::SetOrd;
      3 use alloc::collections::btree_map::{
      4     BTreeMap, CursorMut, IntoIter, IntoKeys, IntoValues, Iter, IterMut, Keys, OccupiedEntry, Range,
      5     RangeMut, Values, ValuesMut,
      6 };
      7 use core::{
      8     borrow::Borrow,
      9     ops::{Bound, Index, RangeBounds},
     10 };
     11 /// A minimal collection of `(K, V)`s.
     12 ///
     13 /// Internally it is based on a [`BTreeMap`]. When a `(K, V)` is [`SupersetMap::insert`]ed, it won't actually be
     14 /// inserted unless there isn't a `K` already in the map that is a superset of it. In such event, all `K`s that
     15 /// are subsets of the to-be-inserted `K` are removed before inserting the `K`.
     16 ///
     17 /// Note this can have quite good performance due to the fact that a single search is necessary to detect if
     18 /// insertion should occur; furthermore since all subsets occur immediately before where the key will be inserted,
     19 /// a simple linear scan is sufficient to remove subsets avoiding the need to search the entire map.
     20 #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
     21 pub struct SupersetMap<K, V> {
     22     /// Collection of `(K, V)`s.
     23     map: BTreeMap<K, V>,
     24 }
     25 impl<K, V> Default for SupersetMap<K, V> {
     26     #[inline]
     27     fn default() -> Self {
     28         Self::new()
     29     }
     30 }
     31 impl<K, V> SupersetMap<K, V> {
     32     /// Read [`BTreeMap::clear`].
     33     #[inline]
     34     pub fn clear(&mut self) {
     35         self.map.clear();
     36     }
     37     /// Read [`BTreeMap::into_keys`].
     38     #[inline]
     39     pub fn into_keys(self) -> IntoKeys<K, V> {
     40         self.map.into_keys()
     41     }
     42     /// Read [`BTreeMap::into_values`].
     43     #[inline]
     44     pub fn into_values(self) -> IntoValues<K, V> {
     45         self.map.into_values()
     46     }
     47     /// Read [`BTreeMap::is_empty`].
     48     #[inline]
     49     #[must_use]
     50     pub fn is_empty(&self) -> bool {
     51         self.map.is_empty()
     52     }
     53     /// Read [`BTreeMap::iter`].
     54     #[inline]
     55     pub fn iter(&self) -> Iter<'_, K, V> {
     56         self.map.iter()
     57     }
     58     /// Read [`BTreeMap::iter_mut`].
     59     #[inline]
     60     pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
     61         self.map.iter_mut()
     62     }
     63     /// Read [`BTreeMap::keys`].
     64     #[inline]
     65     pub fn keys(&self) -> Keys<'_, K, V> {
     66         self.map.keys()
     67     }
     68     /// Read [`BTreeMap::len`].
     69     #[inline]
     70     #[must_use]
     71     pub fn len(&self) -> usize {
     72         self.map.len()
     73     }
     74     /// Makes a new, empty `SupersetMap`.
     75     /// Does not allocate anything on its own.
     76     #[inline]
     77     #[must_use]
     78     pub const fn new() -> Self {
     79         Self {
     80             map: BTreeMap::new(),
     81         }
     82     }
     83     /// Read [`BTreeMap::values`].
     84     #[inline]
     85     pub fn values(&self) -> Values<'_, K, V> {
     86         self.map.values()
     87     }
     88     /// Read [`BTreeMap::values_mut`].
     89     #[inline]
     90     pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
     91         self.map.values_mut()
     92     }
     93 }
     94 impl<K, V> SupersetMap<K, V>
     95 where
     96     K: Ord,
     97 {
     98     /// Read [`BTreeMap::contains_key`].
     99     #[inline]
    100     pub fn contains_key<Q>(&self, key: &Q) -> bool
    101     where
    102         K: Borrow<Q>,
    103         Q: Ord + ?Sized,
    104     {
    105         self.map.contains_key(key)
    106     }
    107     /// Read [`BTreeMap::first_entry`].
    108     #[inline]
    109     pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>> {
    110         self.map.first_entry()
    111     }
    112     /// Read [`BTreeMap::first_key_value`].
    113     #[inline]
    114     #[must_use]
    115     pub fn first_key_value(&self) -> Option<(&K, &V)> {
    116         self.map.first_key_value()
    117     }
    118     /// Read [`BTreeMap::get`].
    119     #[inline]
    120     pub fn get<Q>(&self, key: &Q) -> Option<&V>
    121     where
    122         K: Borrow<Q>,
    123         Q: Ord + ?Sized,
    124     {
    125         self.map.get(key)
    126     }
    127     /// Read [`BTreeMap::get_key_value`].
    128     #[inline]
    129     pub fn get_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
    130     where
    131         K: Borrow<Q>,
    132         Q: Ord + ?Sized,
    133     {
    134         self.map.get_key_value(key)
    135     }
    136     /// Read [`BTreeMap::get_mut`].
    137     #[inline]
    138     pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
    139     where
    140         K: Borrow<Q>,
    141         Q: Ord + ?Sized,
    142     {
    143         self.map.get_mut(key)
    144     }
    145     /// Read [`BTreeMap::last_entry`].
    146     #[inline]
    147     pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>> {
    148         self.map.last_entry()
    149     }
    150     /// Read [`BTreeMap::last_key_value`].
    151     #[inline]
    152     #[must_use]
    153     pub fn last_key_value(&self) -> Option<(&K, &V)> {
    154         self.map.last_key_value()
    155     }
    156     /// Read [`BTreeMap::pop_first`].
    157     #[inline]
    158     pub fn pop_first(&mut self) -> Option<(K, V)> {
    159         self.map.pop_first()
    160     }
    161     /// Read [`BTreeMap::pop_last`].
    162     #[inline]
    163     pub fn pop_last(&mut self) -> Option<(K, V)> {
    164         self.map.pop_last()
    165     }
    166     /// Read [`BTreeMap::range`].
    167     #[inline]
    168     pub fn range<T, R>(&self, range: R) -> Range<'_, K, V>
    169     where
    170         K: Borrow<T>,
    171         T: Ord + ?Sized,
    172         R: RangeBounds<T>,
    173     {
    174         self.map.range(range)
    175     }
    176     /// Read [`BTreeMap::range_mut`].
    177     #[inline]
    178     pub fn range_mut<T, R>(&mut self, range: R) -> RangeMut<'_, K, V>
    179     where
    180         K: Borrow<T>,
    181         T: Ord + ?Sized,
    182         R: RangeBounds<T>,
    183     {
    184         self.map.range_mut(range)
    185     }
    186     /// Read [`BTreeMap::remove`].
    187     #[inline]
    188     pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
    189     where
    190         K: Borrow<Q>,
    191         Q: Ord + ?Sized,
    192     {
    193         self.map.remove(key)
    194     }
    195     /// Read [`BTreeMap::remove_entry`].
    196     #[inline]
    197     pub fn remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
    198     where
    199         K: Borrow<Q>,
    200         Q: Ord + ?Sized,
    201     {
    202         self.map.remove_entry(key)
    203     }
    204     /// Read [`BTreeMap::split_off`].
    205     #[inline]
    206     #[must_use]
    207     pub fn split_off<Q>(&mut self, key: &Q) -> Self
    208     where
    209         K: Borrow<Q>,
    210         Q: Ord + ?Sized,
    211     {
    212         Self {
    213             map: self.map.split_off(key),
    214         }
    215     }
    216 }
    217 impl<K, V> SupersetMap<K, V>
    218 where
    219     K: SetOrd,
    220 {
    221     /// Moves all elements from `other` into `self`, consuming `other`.
    222     /// If a key from `other` is a proper superset of a key in `self`, the respective key and value from `self` will be removed before inserting
    223     /// the key and value from `other`.
    224     /// If a key from `other` is a subset of a key in `self`, it won't be inserted.
    225     #[inline]
    226     pub fn append(&mut self, other: Self) {
    227         if self.is_empty() {
    228             *self = other;
    229         } else {
    230             other.into_iter().fold((), |(), (key, val)| {
    231                 self.insert(key, val);
    232             });
    233         }
    234     }
    235     /// Returns `true` if the map contains a value for a proper subset of the specified key.
    236     /// The key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match the ordering on the key type.
    237     #[inline]
    238     pub fn contains_proper_subset<Q>(&self, key: &Q) -> bool
    239     where
    240         K: Borrow<Q>,
    241         Q: SetOrd + ?Sized,
    242     {
    243         self.get_greatest_proper_subset(key).is_some()
    244     }
    245     /// Returns `true` if the map contains a value for a proper superset of the specified key.
    246     /// The key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match the ordering on the key type.
    247     #[inline]
    248     pub fn contains_proper_superset<Q>(&self, key: &Q) -> bool
    249     where
    250         K: Borrow<Q>,
    251         Q: SetOrd + ?Sized,
    252     {
    253         self.get_least_proper_superset(key).is_some()
    254     }
    255     /// Returns `true` if the map contains a value for a subset of the specified key.
    256     /// The key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match the ordering on the key type.
    257     #[inline]
    258     pub fn contains_subset<Q>(&self, key: &Q) -> bool
    259     where
    260         K: Borrow<Q>,
    261         Q: SetOrd + ?Sized,
    262     {
    263         self.get_greatest_subset(key).is_some()
    264     }
    265     /// Returns `true` if the map contains a value for a superset of the specified key.
    266     /// The key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match the ordering on the key type.
    267     #[inline]
    268     pub fn contains_superset<Q>(&self, key: &Q) -> bool
    269     where
    270         K: Borrow<Q>,
    271         Q: SetOrd + ?Sized,
    272     {
    273         self.get_least_superset(key).is_some()
    274     }
    275     /// Returns a reference to the value corresponding to the greatest proper subset of key.
    276     /// The key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match the ordering on the key type.
    277     #[inline]
    278     pub fn get_greatest_proper_subset<Q>(&self, key: &Q) -> Option<&V>
    279     where
    280         K: Borrow<Q>,
    281         Q: SetOrd + ?Sized,
    282     {
    283         self.get_greatest_proper_subset_key_value(key)
    284             .map(|(_, val)| val)
    285     }
    286     /// Returns a reference to the key-value pair corresponding to the greatest proper subset of the supplied key.
    287     /// The supplied key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match the ordering on the key type
    288     #[inline]
    289     pub fn get_greatest_proper_subset_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
    290     where
    291         K: Borrow<Q>,
    292         Q: SetOrd + ?Sized,
    293     {
    294         self.map
    295             .upper_bound(Bound::Excluded(key))
    296             .peek_prev()
    297             .and_then(|pair| pair.0.borrow().is_proper_subset(key).then_some(pair))
    298     }
    299     /// Returns a reference to the value corresponding to the greatest subset of key.
    300     /// The key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match the ordering on the key type.
    301     #[inline]
    302     pub fn get_greatest_subset<Q>(&self, key: &Q) -> Option<&V>
    303     where
    304         K: Borrow<Q>,
    305         Q: SetOrd + ?Sized,
    306     {
    307         self.get_greatest_subset_key_value(key).map(|(_, val)| val)
    308     }
    309     /// Returns a reference to the key-value pair corresponding to the greatest subset of the supplied key.
    310     /// The supplied key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match the ordering on the key type
    311     #[inline]
    312     pub fn get_greatest_subset_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
    313     where
    314         K: Borrow<Q>,
    315         Q: SetOrd + ?Sized,
    316     {
    317         self.map
    318             .upper_bound(Bound::Included(key))
    319             .peek_prev()
    320             .and_then(|pair| pair.0.borrow().is_subset(key).then_some(pair))
    321     }
    322     /// Returns a reference to the value corresponding to the least proper superset of key.
    323     /// The key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match the ordering on the key type.
    324     #[inline]
    325     pub fn get_least_proper_superset<Q>(&self, key: &Q) -> Option<&V>
    326     where
    327         K: Borrow<Q>,
    328         Q: SetOrd + ?Sized,
    329     {
    330         self.get_least_proper_superset_key_value(key)
    331             .map(|(_, val)| val)
    332     }
    333     /// Returns a reference to the key-value pair corresponding to the least proper superset of the supplied key.
    334     /// The supplied key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match the ordering on the key type
    335     #[inline]
    336     pub fn get_least_proper_superset_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
    337     where
    338         K: Borrow<Q>,
    339         Q: SetOrd + ?Sized,
    340     {
    341         self.map
    342             .lower_bound(Bound::Excluded(key))
    343             .peek_next()
    344             .and_then(|pair| pair.0.borrow().is_proper_superset(key).then_some(pair))
    345     }
    346     /// Returns a reference to the value corresponding to the least superset of key.
    347     /// The key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match the ordering on the key type.
    348     #[inline]
    349     pub fn get_least_superset<Q>(&self, key: &Q) -> Option<&V>
    350     where
    351         K: Borrow<Q>,
    352         Q: SetOrd + ?Sized,
    353     {
    354         self.get_least_superset_key_value(key).map(|(_, val)| val)
    355     }
    356     /// Returns a reference to the key-value pair corresponding to the least superset of the supplied key.
    357     /// The supplied key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match the ordering on the key type
    358     #[inline]
    359     pub fn get_least_superset_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
    360     where
    361         K: Borrow<Q>,
    362         Q: SetOrd + ?Sized,
    363     {
    364         self.map
    365             .lower_bound(Bound::Included(key))
    366             .peek_next()
    367             .and_then(|pair| pair.0.borrow().is_superset(key).then_some(pair))
    368     }
    369     /// `(key, value)` is inserted iff there doesn't already
    370     /// exist a `K` that is a superset of `key`.
    371     /// In the event `(key, value)` will be inserted, all `(K, V)`s
    372     /// where the `K` is a subset of `key` are first removed before
    373     /// inserting.
    374     #[expect(
    375         unsafe_code,
    376         reason = "we rely on CursorMut::insert_before_unchecked since we verify it is safe to do so"
    377     )]
    378     #[inline]
    379     pub fn insert(&mut self, key: K, value: V) -> bool {
    380         // Since the only way to `insert` a `(K, V)` is via this function,
    381         // the following is true:
    382         // The smallest value greater than or equal to `key` will be a superset
    383         // of `key` iff there exists a superset of `key`.
    384         // This means that we simply have to check this one value to decide
    385         // if `(key, value)` needs to be inserted; furthermore, in the event `(key, value)`
    386         // does need to be inserted, we only have to traverse backwards until
    387         // the beginning of `map` or a `K` is not a subset of `key`
    388         // removing all `(K, V)`s where the `K` is a subset before we insert `(key, value)`.
    389         let mut cursor = self.map.lower_bound_mut(Bound::Included(&key));
    390         if let Some(ge) = cursor.peek_next() {
    391             if ge.0.is_superset(&key) {
    392                 return false;
    393             }
    394         }
    395         loop {
    396             match cursor.prev() {
    397                 None => break,
    398                 Some(lt) => {
    399                     if key.is_proper_superset(lt.0) {
    400                         cursor.remove_next();
    401                     } else {
    402                         cursor.next();
    403                         break;
    404                     }
    405                 }
    406             }
    407         }
    408         // SAFETY:
    409         // If `key` already existed in the map, then cursor
    410         // would begin pointing at it. Since `Set::is_superset`
    411         // returns true when both values are the same, we would
    412         // immediately return from this function. This guarantees
    413         // that `key` is unique before inserting.
    414         // Since we only move to smaller values and each time we do
    415         // we remove said value (or stop), the insert of `key` will occur after
    416         // all smaller values and before larger values ensuring the sorted
    417         // order of `map` is retained.
    418         // Note that due to the requirements of `SetOrd`, a `K` that
    419         // `is_proper_superset` another `K` is also strictly greater.
    420         unsafe {
    421             cursor.insert_before_unchecked(key, value);
    422         }
    423         true
    424     }
    425     /// Allows for `SupersetSet::replace` to be implemented for supersets.
    426     #[inline]
    427     pub(crate) fn lower_bound_mut<Q>(&mut self, bound: Bound<&Q>) -> CursorMut<'_, K, V>
    428     where
    429         K: Borrow<Q>,
    430         Q: SetOrd + ?Sized,
    431     {
    432         self.map.lower_bound_mut(bound)
    433     }
    434     /// Removes the greatest proper subset of key from the map, returning the key and value if such a subset exists.
    435     /// The key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match the ordering on the key type.
    436     #[inline]
    437     pub fn remove_greatest_proper_subset<Q>(&mut self, key: &Q) -> Option<(K, V)>
    438     where
    439         K: Borrow<Q>,
    440         Q: SetOrd + ?Sized,
    441     {
    442         let mut cursor = self.map.upper_bound_mut(Bound::Excluded(key));
    443         if let Some(lt) = cursor.peek_prev() {
    444             if lt.0.borrow().is_proper_subset(key) {
    445                 return cursor.remove_prev();
    446             }
    447         }
    448         None
    449     }
    450     /// Removes the greatest subset of key from the map, returning the key and value if such a subset exists.
    451     /// The key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match the ordering on the key type.
    452     #[inline]
    453     pub fn remove_greatest_subset<Q>(&mut self, key: &Q) -> Option<(K, V)>
    454     where
    455         K: Borrow<Q>,
    456         Q: SetOrd + ?Sized,
    457     {
    458         let mut cursor = self.map.upper_bound_mut(Bound::Included(key));
    459         if let Some(le) = cursor.peek_prev() {
    460             if le.0.borrow().is_subset(key) {
    461                 return cursor.remove_prev();
    462             }
    463         }
    464         None
    465     }
    466     /// Removes the least proper superset of key from the map, returning the key and value if such a superset exists.
    467     /// The key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match the ordering on the key type.
    468     #[inline]
    469     pub fn remove_least_proper_superset<Q>(&mut self, key: &Q) -> Option<(K, V)>
    470     where
    471         K: Borrow<Q>,
    472         Q: SetOrd + ?Sized,
    473     {
    474         let mut cursor = self.map.lower_bound_mut(Bound::Excluded(key));
    475         if let Some(gt) = cursor.peek_next() {
    476             if gt.0.borrow().is_proper_superset(key) {
    477                 return cursor.remove_next();
    478             }
    479         }
    480         None
    481     }
    482     /// Removes the least superset of key from the map, returning the key and value if such a superset exists.
    483     /// The key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match the ordering on the key type.
    484     #[inline]
    485     pub fn remove_least_superset<Q>(&mut self, key: &Q) -> Option<(K, V)>
    486     where
    487         K: Borrow<Q>,
    488         Q: SetOrd + ?Sized,
    489     {
    490         let mut cursor = self.map.lower_bound_mut(Bound::Included(key));
    491         if let Some(ge) = cursor.peek_next() {
    492             if ge.0.borrow().is_superset(key) {
    493                 return cursor.remove_next();
    494             }
    495         }
    496         None
    497     }
    498     /// Removes all proper subsets of key from the map, returning the count removed.
    499     /// The key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match
    500     /// the ordering on the key type.
    501     #[expect(
    502         clippy::arithmetic_side_effects,
    503         reason = "we count how many items are removed which can never exceed the length"
    504     )]
    505     #[inline]
    506     pub fn remove_proper_subsets<Q>(&mut self, key: &Q) -> usize
    507     where
    508         K: Borrow<Q>,
    509         Q: SetOrd + ?Sized,
    510     {
    511         let mut cursor = self.map.upper_bound_mut(Bound::Excluded(key));
    512         let mut count = 0;
    513         while let Some(lt) = cursor.prev() {
    514             if lt.0.borrow().is_proper_subset(key) {
    515                 cursor.remove_next();
    516                 count += 1;
    517             } else {
    518                 return count;
    519             }
    520         }
    521         count
    522     }
    523     /// Removes all proper supersets of key from the map, returning the count removed.
    524     /// The key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match
    525     /// the ordering on the key type.
    526     #[expect(
    527         clippy::arithmetic_side_effects,
    528         reason = "we count how many items are removed which can never exceed the length"
    529     )]
    530     #[inline]
    531     pub fn remove_proper_supersets<Q>(&mut self, key: &Q) -> usize
    532     where
    533         K: Borrow<Q>,
    534         Q: SetOrd + ?Sized,
    535     {
    536         let mut cursor = self.map.lower_bound_mut(Bound::Excluded(key));
    537         let mut count = 0;
    538         while let Some(gt) = cursor.next() {
    539             if gt.0.borrow().is_proper_superset(key) {
    540                 cursor.remove_prev();
    541                 count += 1;
    542             } else {
    543                 return count;
    544             }
    545         }
    546         count
    547     }
    548     /// Removes all subsets of key from the map, returning the count removed.
    549     /// The key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match
    550     /// the ordering on the key type.
    551     #[expect(
    552         clippy::arithmetic_side_effects,
    553         reason = "we count how many items are removed which can never exceed the length"
    554     )]
    555     #[inline]
    556     pub fn remove_subsets<Q>(&mut self, key: &Q) -> usize
    557     where
    558         K: Borrow<Q>,
    559         Q: SetOrd + ?Sized,
    560     {
    561         let mut cursor = self.map.upper_bound_mut(Bound::Included(key));
    562         let mut count = 0;
    563         // To avoid unnecessary checks for equivalence,
    564         // we separately call `is_subset` on the first element
    565         // while calling `is_proper_subset` on the other elements.
    566         if let Some(le) = cursor.prev() {
    567             if le.0.borrow().is_subset(key) {
    568                 cursor.remove_next();
    569                 count += 1;
    570                 while let Some(lt) = cursor.prev() {
    571                     if lt.0.borrow().is_proper_subset(key) {
    572                         cursor.remove_next();
    573                         count += 1;
    574                     } else {
    575                         return count;
    576                     }
    577                 }
    578             } else {
    579                 return count;
    580             }
    581         }
    582         count
    583     }
    584     /// Removes all supersets of key from the map, returning the count removed.
    585     /// The key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must
    586     /// match the ordering on the key type.
    587     #[expect(
    588         clippy::arithmetic_side_effects,
    589         reason = "we count how many items are removed which can never exceed the length"
    590     )]
    591     #[inline]
    592     pub fn remove_supersets<Q>(&mut self, key: &Q) -> usize
    593     where
    594         K: Borrow<Q>,
    595         Q: SetOrd + ?Sized,
    596     {
    597         let mut cursor = self.map.lower_bound_mut(Bound::Included(key));
    598         let mut count = 0;
    599         // To avoid unnecessary checks for equivalence, // we separately call `is_superset` on the first element
    600         // while calling `is_proper_superset` on the other elements.
    601         if let Some(ge) = cursor.next() {
    602             if ge.0.borrow().is_superset(key) {
    603                 cursor.remove_prev();
    604                 // `count` never exceeds `self.map.len()`; thus overflow is no worry.
    605                 count += 1;
    606                 while let Some(gt) = cursor.next() {
    607                     if gt.0.borrow().is_proper_superset(key) {
    608                         cursor.remove_prev();
    609                         // `count` never exceeds `self.map.len()`; thus overflow is no worry.
    610                         count += 1;
    611                     } else {
    612                         return count;
    613                     }
    614                 }
    615             } else {
    616                 return count;
    617             }
    618         }
    619         count
    620     }
    621     /// Retains only the elements specified by the predicate.
    622     /// In other words, remove all pairs `(k, v)` for which `f(&k, &mut v)` returns `false`. The elements are visited in ascending key order.
    623     #[inline]
    624     pub fn retain<F>(&mut self, f: F)
    625     where
    626         F: FnMut(&K, &mut V) -> bool,
    627     {
    628         self.map.retain(f);
    629     }
    630 }
    631 impl<K, V> Extend<(K, V)> for SupersetMap<K, V>
    632 where
    633     K: SetOrd,
    634 {
    635     #[inline]
    636     fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
    637         iter.into_iter().fold((), |(), (k, v)| {
    638             self.insert(k, v);
    639         });
    640     }
    641 }
    642 impl<'a, K, V> Extend<(&'a K, &'a V)> for SupersetMap<K, V>
    643 where
    644     K: SetOrd + Copy,
    645     V: Copy,
    646 {
    647     #[inline]
    648     fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
    649         iter.into_iter().fold((), |(), (k, v)| {
    650             self.insert(*k, *v);
    651         });
    652     }
    653 }
    654 impl<K, V, const N: usize> From<[(K, V); N]> for SupersetMap<K, V>
    655 where
    656     K: SetOrd,
    657 {
    658     #[inline]
    659     fn from(value: [(K, V); N]) -> Self {
    660         let mut map = Self::new();
    661         map.extend(value);
    662         map
    663     }
    664 }
    665 impl<K, V> FromIterator<(K, V)> for SupersetMap<K, V>
    666 where
    667     K: SetOrd,
    668 {
    669     #[inline]
    670     fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
    671         let mut map = Self::new();
    672         map.extend(iter);
    673         map
    674     }
    675 }
    676 impl<K, Q, V> Index<&Q> for SupersetMap<K, V>
    677 where
    678     K: Borrow<Q> + Ord,
    679     Q: Ord + ?Sized,
    680 {
    681     type Output = V;
    682     #[inline]
    683     fn index(&self, index: &Q) -> &Self::Output {
    684         self.map.index(index)
    685     }
    686 }
    687 impl<K, V> IntoIterator for SupersetMap<K, V> {
    688     type Item = (K, V);
    689     type IntoIter = IntoIter<K, V>;
    690     #[inline]
    691     fn into_iter(self) -> Self::IntoIter {
    692         self.map.into_iter()
    693     }
    694 }
    695 impl<'a, K, V> IntoIterator for &'a SupersetMap<K, V> {
    696     type Item = (&'a K, &'a V);
    697     type IntoIter = Iter<'a, K, V>;
    698     #[inline]
    699     fn into_iter(self) -> Self::IntoIter {
    700         self.iter()
    701     }
    702 }
    703 impl<'a, K, V> IntoIterator for &'a mut SupersetMap<K, V> {
    704     type Item = (&'a K, &'a mut V);
    705     type IntoIter = IterMut<'a, K, V>;
    706     #[inline]
    707     fn into_iter(self) -> Self::IntoIter {
    708         self.iter_mut()
    709     }
    710 }
    711 #[cfg(test)]
    712 mod tests {
    713     use super::{
    714         super::zfc::{num_bigint::BigUint, BoundedCardinality, Cardinality, Set},
    715         SetOrd, SupersetMap,
    716     };
    717     use core::{borrow::Borrow, cmp::Ordering};
    718     #[derive(Eq, PartialEq)]
    719     struct ClosedInterval {
    720         min: usize,
    721         max: usize,
    722     }
    723     impl PartialOrd<Self> for ClosedInterval {
    724         fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
    725             Some(self.cmp(other))
    726         }
    727     }
    728     impl Ord for ClosedInterval {
    729         fn cmp(&self, other: &Self) -> Ordering {
    730             match self.min.cmp(&other.min) {
    731                 Ordering::Less => {
    732                     if self.max >= other.max {
    733                         Ordering::Greater
    734                     } else {
    735                         Ordering::Less
    736                     }
    737                 }
    738                 Ordering::Equal => self.max.cmp(&other.max),
    739                 Ordering::Greater => {
    740                     if self.max > other.max {
    741                         Ordering::Greater
    742                     } else {
    743                         Ordering::Less
    744                     }
    745                 }
    746             }
    747         }
    748     }
    749     impl Set for ClosedInterval {
    750         type Elem = usize;
    751         fn bounded_cardinality(&self) -> BoundedCardinality {
    752             BoundedCardinality::from_biguint_exact(
    753                 BigUint::from(self.max - self.min) + BigUint::from(1usize),
    754             )
    755         }
    756         fn cardinality(&self) -> Option<Cardinality> {
    757             Some(Cardinality::Finite(
    758                 BigUint::from(self.max - self.min) + BigUint::from(1usize),
    759             ))
    760         }
    761         fn contains<Q>(&self, elem: &Q) -> bool
    762         where
    763             Q: ?Sized + Borrow<Self::Elem> + Eq,
    764         {
    765             self.min <= *elem.borrow() && self.max >= *elem.borrow()
    766         }
    767         fn is_proper_subset(&self, val: &Self) -> bool {
    768             match self.min.cmp(&val.min) {
    769                 Ordering::Less => false,
    770                 Ordering::Equal => self.max < val.max,
    771                 Ordering::Greater => self.max <= val.max,
    772             }
    773         }
    774         fn is_subset(&self, val: &Self) -> bool {
    775             self.min >= val.min && self.max <= val.max
    776         }
    777     }
    778     impl SetOrd for ClosedInterval {}
    779     #[test]
    780     fn test_insert() {
    781         let mut map = SupersetMap::new();
    782         map.insert(ClosedInterval { min: 0, max: 3 }, ());
    783         map.insert(ClosedInterval { min: 0, max: 3 }, ());
    784         map.insert(ClosedInterval { min: 0, max: 4 }, ());
    785         map.insert(ClosedInterval { min: 1, max: 4 }, ());
    786         map.insert(ClosedInterval { min: 4, max: 6 }, ());
    787         map.insert(ClosedInterval { min: 2, max: 7 }, ());
    788         map.insert(ClosedInterval { min: 10, max: 17 }, ());
    789         let mut keys = map.into_keys();
    790         assert!(keys
    791             .next()
    792             .map_or(false, |set| set == ClosedInterval { min: 0, max: 4 }));
    793         assert!(keys
    794             .next()
    795             .map_or(false, |set| set == ClosedInterval { min: 2, max: 7 }));
    796         assert!(keys
    797             .next()
    798             .map_or(false, |set| set == ClosedInterval { min: 10, max: 17 }));
    799         assert!(keys.next().is_none());
    800         assert!(keys.next().is_none());
    801         assert!(keys.next().is_none());
    802     }
    803     #[test]
    804     fn test_append() {
    805         let mut map = SupersetMap::new();
    806         map.insert(ClosedInterval { min: 0, max: 3 }, ());
    807         map.insert(ClosedInterval { min: 0, max: 3 }, ());
    808         map.insert(ClosedInterval { min: 0, max: 4 }, ());
    809         map.insert(ClosedInterval { min: 1, max: 4 }, ());
    810         map.insert(ClosedInterval { min: 4, max: 6 }, ());
    811         map.insert(ClosedInterval { min: 2, max: 7 }, ());
    812         map.insert(ClosedInterval { min: 10, max: 17 }, ());
    813         let mut map2 = SupersetMap::new();
    814         map2.insert(ClosedInterval { min: 0, max: 1 }, ());
    815         map2.insert(ClosedInterval { min: 1, max: 14 }, ());
    816         map2.insert(ClosedInterval { min: 11, max: 18 }, ());
    817         map.append(map2);
    818         let mut keys = map.into_keys();
    819         assert!(keys
    820             .next()
    821             .map_or(false, |set| set == ClosedInterval { min: 0, max: 4 }));
    822         assert!(keys
    823             .next()
    824             .map_or(false, |set| set == ClosedInterval { min: 1, max: 14 }));
    825         assert!(keys
    826             .next()
    827             .map_or(false, |set| set == ClosedInterval { min: 10, max: 17 }));
    828         assert!(keys
    829             .next()
    830             .map_or(false, |set| set == ClosedInterval { min: 11, max: 18 }));
    831         assert!(keys.next().is_none());
    832         assert!(keys.next().is_none());
    833         assert!(keys.next().is_none());
    834     }
    835     #[test]
    836     fn test_contains() {
    837         let mut map = SupersetMap::new();
    838         map.insert(ClosedInterval { min: 0, max: 3 }, ());
    839         map.insert(ClosedInterval { min: 0, max: 3 }, ());
    840         map.insert(ClosedInterval { min: 0, max: 4 }, ());
    841         map.insert(ClosedInterval { min: 1, max: 4 }, ());
    842         map.insert(ClosedInterval { min: 4, max: 6 }, ());
    843         map.insert(ClosedInterval { min: 2, max: 7 }, ());
    844         map.insert(ClosedInterval { min: 10, max: 17 }, ());
    845         assert!(map.contains_proper_subset(&ClosedInterval { min: 0, max: 10 }));
    846         assert!(!map.contains_proper_subset(&ClosedInterval { min: 10, max: 17 }));
    847         assert!(!map.contains_proper_subset(&ClosedInterval { min: 210, max: 217 }));
    848         assert!(map.contains_proper_superset(&ClosedInterval { min: 0, max: 1 }));
    849         assert!(!map.contains_proper_superset(&ClosedInterval { min: 10, max: 17 }));
    850         assert!(!map.contains_proper_superset(&ClosedInterval { min: 210, max: 217 }));
    851         assert!(map.contains_subset(&ClosedInterval { min: 0, max: 10 }));
    852         assert!(map.contains_subset(&ClosedInterval { min: 10, max: 17 }));
    853         assert!(!map.contains_subset(&ClosedInterval { min: 210, max: 217 }));
    854         assert!(map.contains_superset(&ClosedInterval { min: 0, max: 1 }));
    855         assert!(map.contains_superset(&ClosedInterval { min: 10, max: 17 }));
    856         assert!(!map.contains_superset(&ClosedInterval { min: 210, max: 217 }));
    857     }
    858     #[test]
    859     fn test_get() {
    860         let mut map = SupersetMap::new();
    861         map.insert(ClosedInterval { min: 0, max: 3 }, ());
    862         map.insert(ClosedInterval { min: 0, max: 3 }, ());
    863         map.insert(ClosedInterval { min: 0, max: 4 }, ());
    864         map.insert(ClosedInterval { min: 1, max: 4 }, ());
    865         map.insert(ClosedInterval { min: 4, max: 6 }, ());
    866         map.insert(ClosedInterval { min: 2, max: 7 }, ());
    867         map.insert(ClosedInterval { min: 10, max: 17 }, ());
    868         assert!(map
    869             .get_greatest_proper_subset_key_value(&ClosedInterval { min: 0, max: 10 })
    870             .map_or(false, |(key, _)| *key == ClosedInterval { min: 2, max: 7 }));
    871         assert!(map
    872             .get_greatest_proper_subset_key_value(&ClosedInterval { min: 10, max: 17 })
    873             .map_or(true, |_| false));
    874         assert!(map
    875             .get_greatest_proper_subset_key_value(&ClosedInterval { min: 210, max: 217 })
    876             .map_or(true, |_| false));
    877         assert!(map
    878             .get_least_proper_superset_key_value(&ClosedInterval { min: 3, max: 4 })
    879             .map_or(false, |(key, _)| *key == ClosedInterval { min: 0, max: 4 }));
    880         assert!(map
    881             .get_least_proper_superset_key_value(&ClosedInterval { min: 10, max: 17 })
    882             .map_or(true, |_| false));
    883         assert!(map
    884             .get_least_proper_superset_key_value(&ClosedInterval { min: 210, max: 217 })
    885             .map_or(true, |_| false));
    886         assert!(map
    887             .get_greatest_subset_key_value(&ClosedInterval { min: 0, max: 10 })
    888             .map_or(false, |(key, _)| *key == ClosedInterval { min: 2, max: 7 }));
    889         assert!(map
    890             .get_greatest_subset_key_value(&ClosedInterval { min: 10, max: 17 })
    891             .map_or(false, |(key, _)| *key
    892                 == ClosedInterval { min: 10, max: 17 }));
    893         assert!(map
    894             .get_greatest_subset_key_value(&ClosedInterval { min: 210, max: 217 })
    895             .map_or(true, |_| false));
    896         assert!(map
    897             .get_least_superset_key_value(&ClosedInterval { min: 3, max: 4 })
    898             .map_or(false, |(key, _)| *key == ClosedInterval { min: 0, max: 4 }));
    899         assert!(map
    900             .get_least_superset_key_value(&ClosedInterval { min: 10, max: 17 })
    901             .map_or(false, |(key, _)| *key
    902                 == ClosedInterval { min: 10, max: 17 }));
    903         assert!(map
    904             .get_least_superset_key_value(&ClosedInterval { min: 210, max: 217 })
    905             .map_or(true, |_| false));
    906     }
    907     #[test]
    908     fn test_remove() {
    909         let mut map = SupersetMap::new();
    910         map.insert(ClosedInterval { min: 0, max: 3 }, ());
    911         map.insert(ClosedInterval { min: 0, max: 3 }, ());
    912         map.insert(ClosedInterval { min: 0, max: 4 }, ());
    913         map.insert(ClosedInterval { min: 1, max: 4 }, ());
    914         map.insert(ClosedInterval { min: 4, max: 6 }, ());
    915         map.insert(ClosedInterval { min: 2, max: 7 }, ());
    916         map.insert(ClosedInterval { min: 10, max: 17 }, ());
    917         assert!(map
    918             .remove_greatest_proper_subset(&ClosedInterval { min: 0, max: 10 })
    919             .map_or(false, |(key, _)| key == ClosedInterval { min: 2, max: 7 }));
    920         assert!(map
    921             .remove_greatest_proper_subset(&ClosedInterval { min: 10, max: 17 })
    922             .map_or(true, |_| false));
    923         assert!(map
    924             .remove_greatest_proper_subset(&ClosedInterval { min: 210, max: 217 })
    925             .map_or(true, |_| false));
    926         assert!(map
    927             .remove_least_proper_superset(&ClosedInterval { min: 3, max: 4 })
    928             .map_or(false, |(key, _)| key == ClosedInterval { min: 0, max: 4 }));
    929         assert!(map
    930             .remove_least_proper_superset(&ClosedInterval { min: 10, max: 17 })
    931             .map_or(true, |_| false));
    932         assert!(map
    933             .remove_least_proper_superset(&ClosedInterval { min: 210, max: 217 })
    934             .map_or(true, |_| false));
    935         assert!(map
    936             .remove_greatest_subset(&ClosedInterval { min: 0, max: 10 })
    937             .map_or(true, |_| false));
    938         assert!(map
    939             .remove_greatest_subset(&ClosedInterval { min: 10, max: 17 })
    940             .map_or(false, |(key, _)| key == ClosedInterval { min: 10, max: 17 }));
    941         assert!(map
    942             .remove_greatest_subset(&ClosedInterval { min: 210, max: 217 })
    943             .map_or(true, |_| false));
    944         assert!(map
    945             .remove_least_superset(&ClosedInterval { min: 3, max: 4 })
    946             .map_or(true, |_| false));
    947         assert!(map
    948             .remove_least_superset(&ClosedInterval { min: 10, max: 17 })
    949             .map_or(true, |_| false));
    950         assert!(map
    951             .remove_least_superset(&ClosedInterval { min: 210, max: 217 })
    952             .map_or(true, |_| false));
    953         let mut map2 = SupersetMap::new();
    954         map2.insert(ClosedInterval { min: 0, max: 3 }, ());
    955         map2.insert(ClosedInterval { min: 0, max: 3 }, ());
    956         map2.insert(ClosedInterval { min: 0, max: 4 }, ());
    957         map2.insert(ClosedInterval { min: 1, max: 4 }, ());
    958         map2.insert(ClosedInterval { min: 4, max: 6 }, ());
    959         map2.insert(ClosedInterval { min: 2, max: 7 }, ());
    960         map2.insert(ClosedInterval { min: 10, max: 17 }, ());
    961         assert!(map2.remove_supersets(&ClosedInterval { min: 0, max: 20 }) == 0);
    962         assert!(map2.remove_subsets(&ClosedInterval { min: 0, max: 1 }) == 0);
    963         assert!(map2.remove_subsets(&ClosedInterval { min: 0, max: 20 }) == 3);
    964         map2.insert(ClosedInterval { min: 0, max: 3 }, ());
    965         map2.insert(ClosedInterval { min: 0, max: 3 }, ());
    966         map2.insert(ClosedInterval { min: 0, max: 4 }, ());
    967         map2.insert(ClosedInterval { min: 1, max: 4 }, ());
    968         map2.insert(ClosedInterval { min: 4, max: 6 }, ());
    969         map2.insert(ClosedInterval { min: 2, max: 7 }, ());
    970         map2.insert(ClosedInterval { min: 10, max: 17 }, ());
    971         assert!(map2.remove_supersets(&ClosedInterval { min: 3, max: 4 }) == 2);
    972     }
    973 }