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 (38371B)


      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             && ge.0.is_superset(&key)
    392         {
    393             false
    394         } else {
    395             loop {
    396                 match cursor.prev() {
    397                     None => break,
    398                     Some(lt) => {
    399                         if key.is_proper_superset(lt.0) {
    400                             drop(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     }
    426     /// Allows for `SupersetSet::replace` to be implemented for supersets.
    427     #[inline]
    428     pub(crate) fn lower_bound_mut<Q>(&mut self, bound: Bound<&Q>) -> CursorMut<'_, K, V>
    429     where
    430         K: Borrow<Q>,
    431         Q: SetOrd + ?Sized,
    432     {
    433         self.map.lower_bound_mut(bound)
    434     }
    435     /// Removes the greatest proper subset of key from the map, returning the key and value if such a subset exists.
    436     /// 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.
    437     #[inline]
    438     pub fn remove_greatest_proper_subset<Q>(&mut self, key: &Q) -> Option<(K, V)>
    439     where
    440         K: Borrow<Q>,
    441         Q: SetOrd + ?Sized,
    442     {
    443         let mut cursor = self.map.upper_bound_mut(Bound::Excluded(key));
    444         if let Some(lt) = cursor.peek_prev()
    445             && lt.0.borrow().is_proper_subset(key)
    446         {
    447             cursor.remove_prev()
    448         } else {
    449             None
    450         }
    451     }
    452     /// Removes the greatest subset of key from the map, returning the key and value if such a subset exists.
    453     /// 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.
    454     #[inline]
    455     pub fn remove_greatest_subset<Q>(&mut self, key: &Q) -> Option<(K, V)>
    456     where
    457         K: Borrow<Q>,
    458         Q: SetOrd + ?Sized,
    459     {
    460         let mut cursor = self.map.upper_bound_mut(Bound::Included(key));
    461         if let Some(le) = cursor.peek_prev()
    462             && le.0.borrow().is_subset(key)
    463         {
    464             cursor.remove_prev()
    465         } else {
    466             None
    467         }
    468     }
    469     /// Removes the least proper superset of key from the map, returning the key and value if such a superset exists.
    470     /// 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.
    471     #[inline]
    472     pub fn remove_least_proper_superset<Q>(&mut self, key: &Q) -> Option<(K, V)>
    473     where
    474         K: Borrow<Q>,
    475         Q: SetOrd + ?Sized,
    476     {
    477         let mut cursor = self.map.lower_bound_mut(Bound::Excluded(key));
    478         if let Some(gt) = cursor.peek_next()
    479             && gt.0.borrow().is_proper_superset(key)
    480         {
    481             cursor.remove_next()
    482         } else {
    483             None
    484         }
    485     }
    486     /// Removes the least superset of key from the map, returning the key and value if such a superset exists.
    487     /// 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.
    488     #[inline]
    489     pub fn remove_least_superset<Q>(&mut self, key: &Q) -> Option<(K, V)>
    490     where
    491         K: Borrow<Q>,
    492         Q: SetOrd + ?Sized,
    493     {
    494         let mut cursor = self.map.lower_bound_mut(Bound::Included(key));
    495         if let Some(ge) = cursor.peek_next()
    496             && ge.0.borrow().is_superset(key)
    497         {
    498             cursor.remove_next()
    499         } else {
    500             None
    501         }
    502     }
    503     /// Removes all proper subsets of key from the map, returning the count removed.
    504     /// The key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match
    505     /// the ordering on the key type.
    506     #[expect(
    507         clippy::arithmetic_side_effects,
    508         reason = "we count how many items are removed which can never exceed the length"
    509     )]
    510     #[inline]
    511     pub fn remove_proper_subsets<Q>(&mut self, key: &Q) -> usize
    512     where
    513         K: Borrow<Q>,
    514         Q: SetOrd + ?Sized,
    515     {
    516         let mut cursor = self.map.upper_bound_mut(Bound::Excluded(key));
    517         let mut count = 0;
    518         while let Some(lt) = cursor.prev() {
    519             if lt.0.borrow().is_proper_subset(key) {
    520                 drop(cursor.remove_next());
    521                 count += 1;
    522             } else {
    523                 return count;
    524             }
    525         }
    526         count
    527     }
    528     /// Removes all proper supersets of key from the map, returning the count removed.
    529     /// The key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match
    530     /// the ordering on the key type.
    531     #[expect(
    532         clippy::arithmetic_side_effects,
    533         reason = "we count how many items are removed which can never exceed the length"
    534     )]
    535     #[inline]
    536     pub fn remove_proper_supersets<Q>(&mut self, key: &Q) -> usize
    537     where
    538         K: Borrow<Q>,
    539         Q: SetOrd + ?Sized,
    540     {
    541         let mut cursor = self.map.lower_bound_mut(Bound::Excluded(key));
    542         let mut count = 0;
    543         while let Some(gt) = cursor.next() {
    544             if gt.0.borrow().is_proper_superset(key) {
    545                 drop(cursor.remove_prev());
    546                 count += 1;
    547             } else {
    548                 return count;
    549             }
    550         }
    551         count
    552     }
    553     /// Removes all subsets of key from the map, returning the count removed.
    554     /// The key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match
    555     /// the ordering on the key type.
    556     #[expect(
    557         clippy::arithmetic_side_effects,
    558         reason = "we count how many items are removed which can never exceed the length"
    559     )]
    560     #[inline]
    561     pub fn remove_subsets<Q>(&mut self, key: &Q) -> usize
    562     where
    563         K: Borrow<Q>,
    564         Q: SetOrd + ?Sized,
    565     {
    566         let mut cursor = self.map.upper_bound_mut(Bound::Included(key));
    567         let mut count = 0;
    568         // To avoid unnecessary checks for equivalence,
    569         // we separately call `is_subset` on the first element
    570         // while calling `is_proper_subset` on the other elements.
    571         if let Some(le) = cursor.prev() {
    572             if le.0.borrow().is_subset(key) {
    573                 drop(cursor.remove_next());
    574                 count += 1;
    575                 while let Some(lt) = cursor.prev() {
    576                     if lt.0.borrow().is_proper_subset(key) {
    577                         drop(cursor.remove_next());
    578                         count += 1;
    579                     } else {
    580                         return count;
    581                     }
    582                 }
    583             } else {
    584                 return count;
    585             }
    586         }
    587         count
    588     }
    589     /// Removes all supersets of key from the map, returning the count removed.
    590     /// The key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must
    591     /// match the ordering on the key type.
    592     #[expect(
    593         clippy::arithmetic_side_effects,
    594         reason = "we count how many items are removed which can never exceed the length"
    595     )]
    596     #[inline]
    597     pub fn remove_supersets<Q>(&mut self, key: &Q) -> usize
    598     where
    599         K: Borrow<Q>,
    600         Q: SetOrd + ?Sized,
    601     {
    602         let mut cursor = self.map.lower_bound_mut(Bound::Included(key));
    603         let mut count = 0;
    604         // To avoid unnecessary checks for equivalence, // we separately call `is_superset` on the first element
    605         // while calling `is_proper_superset` on the other elements.
    606         if let Some(ge) = cursor.next() {
    607             if ge.0.borrow().is_superset(key) {
    608                 drop(cursor.remove_prev());
    609                 // `count` never exceeds `self.map.len()`; thus overflow is no worry.
    610                 count += 1;
    611                 while let Some(gt) = cursor.next() {
    612                     if gt.0.borrow().is_proper_superset(key) {
    613                         drop(cursor.remove_prev());
    614                         // `count` never exceeds `self.map.len()`; thus overflow is no worry.
    615                         count += 1;
    616                     } else {
    617                         return count;
    618                     }
    619                 }
    620             } else {
    621                 return count;
    622             }
    623         }
    624         count
    625     }
    626     /// Retains only the elements specified by the predicate.
    627     /// In other words, remove all pairs `(k, v)` for which `f(&k, &mut v)` returns `false`. The elements are visited in ascending key order.
    628     #[inline]
    629     pub fn retain<F>(&mut self, f: F)
    630     where
    631         F: FnMut(&K, &mut V) -> bool,
    632     {
    633         self.map.retain(f);
    634     }
    635 }
    636 impl<K, V> Extend<(K, V)> for SupersetMap<K, V>
    637 where
    638     K: SetOrd,
    639 {
    640     #[inline]
    641     fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
    642         iter.into_iter().fold((), |(), (k, v)| {
    643             _ = self.insert(k, v);
    644         });
    645     }
    646 }
    647 impl<'a, K, V> Extend<(&'a K, &'a V)> for SupersetMap<K, V>
    648 where
    649     K: SetOrd + Copy,
    650     V: Copy,
    651 {
    652     #[inline]
    653     fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
    654         iter.into_iter().fold((), |(), (k, v)| {
    655             _ = self.insert(*k, *v);
    656         });
    657     }
    658 }
    659 impl<K, V, const N: usize> From<[(K, V); N]> for SupersetMap<K, V>
    660 where
    661     K: SetOrd,
    662 {
    663     #[inline]
    664     fn from(value: [(K, V); N]) -> Self {
    665         let mut map = Self::new();
    666         map.extend(value);
    667         map
    668     }
    669 }
    670 impl<K, V> FromIterator<(K, V)> for SupersetMap<K, V>
    671 where
    672     K: SetOrd,
    673 {
    674     #[inline]
    675     fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
    676         let mut map = Self::new();
    677         map.extend(iter);
    678         map
    679     }
    680 }
    681 impl<K, Q, V> Index<&Q> for SupersetMap<K, V>
    682 where
    683     K: Borrow<Q> + Ord,
    684     Q: Ord + ?Sized,
    685 {
    686     type Output = V;
    687     #[inline]
    688     fn index(&self, index: &Q) -> &Self::Output {
    689         self.map.index(index)
    690     }
    691 }
    692 impl<K, V> IntoIterator for SupersetMap<K, V> {
    693     type Item = (K, V);
    694     type IntoIter = IntoIter<K, V>;
    695     #[inline]
    696     fn into_iter(self) -> Self::IntoIter {
    697         self.map.into_iter()
    698     }
    699 }
    700 impl<'a, K, V> IntoIterator for &'a SupersetMap<K, V> {
    701     type Item = (&'a K, &'a V);
    702     type IntoIter = Iter<'a, K, V>;
    703     #[inline]
    704     fn into_iter(self) -> Self::IntoIter {
    705         self.iter()
    706     }
    707 }
    708 impl<'a, K, V> IntoIterator for &'a mut SupersetMap<K, V> {
    709     type Item = (&'a K, &'a mut V);
    710     type IntoIter = IterMut<'a, K, V>;
    711     #[inline]
    712     fn into_iter(self) -> Self::IntoIter {
    713         self.iter_mut()
    714     }
    715 }
    716 #[cfg(test)]
    717 mod tests {
    718     use super::{
    719         super::zfc::{BoundedCardinality, Cardinality, Set, num_bigint::BigUint},
    720         SetOrd, SupersetMap,
    721     };
    722     use core::{borrow::Borrow, cmp::Ordering};
    723     #[derive(Eq, PartialEq)]
    724     struct ClosedInterval {
    725         min: usize,
    726         max: usize,
    727     }
    728     impl PartialOrd<Self> for ClosedInterval {
    729         fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
    730             Some(self.cmp(other))
    731         }
    732     }
    733     impl Ord for ClosedInterval {
    734         fn cmp(&self, other: &Self) -> Ordering {
    735             match self.min.cmp(&other.min) {
    736                 Ordering::Less => {
    737                     if self.max >= other.max {
    738                         Ordering::Greater
    739                     } else {
    740                         Ordering::Less
    741                     }
    742                 }
    743                 Ordering::Equal => self.max.cmp(&other.max),
    744                 Ordering::Greater => {
    745                     if self.max > other.max {
    746                         Ordering::Greater
    747                     } else {
    748                         Ordering::Less
    749                     }
    750                 }
    751             }
    752         }
    753     }
    754     impl Set for ClosedInterval {
    755         type Elem = usize;
    756         #[expect(clippy::panic, reason = "want to crash when there is a bug")]
    757         #[expect(
    758             clippy::arithmetic_side_effects,
    759             reason = "comment justifies correctness"
    760         )]
    761         fn bounded_cardinality(&self) -> BoundedCardinality {
    762             BoundedCardinality::from_biguint_exact(
    763                 // We can add `BigUint`s.
    764                 BigUint::from(self.max.checked_sub(self.min).unwrap_or_else(|| {
    765                     panic!(
    766                         "superset_map::test::ClosedInterval must be created such that max is >= min"
    767                     )
    768                 })) + BigUint::from(1usize),
    769             )
    770         }
    771         #[expect(clippy::panic, reason = "want to crash when there is a bug")]
    772         #[expect(
    773             clippy::arithmetic_side_effects,
    774             reason = "comment justifies correctness"
    775         )]
    776         fn cardinality(&self) -> Option<Cardinality> {
    777             Some(Cardinality::Finite(
    778                 // We can add `BigUint`s.
    779                 BigUint::from(self.max.checked_sub(self.min).unwrap_or_else(|| {
    780                     panic!(
    781                         "superset_map::test::ClosedInterval must be created such that max is >= min"
    782                     )
    783                 })) + BigUint::from(1usize),
    784             ))
    785         }
    786         fn contains<Q>(&self, elem: &Q) -> bool
    787         where
    788             Q: ?Sized + Borrow<Self::Elem> + Eq,
    789         {
    790             self.min <= *elem.borrow() && self.max >= *elem.borrow()
    791         }
    792         fn is_proper_subset(&self, val: &Self) -> bool {
    793             match self.min.cmp(&val.min) {
    794                 Ordering::Less => false,
    795                 Ordering::Equal => self.max < val.max,
    796                 Ordering::Greater => self.max <= val.max,
    797             }
    798         }
    799         fn is_subset(&self, val: &Self) -> bool {
    800             self.min >= val.min && self.max <= val.max
    801         }
    802     }
    803     impl SetOrd for ClosedInterval {}
    804     #[test]
    805     fn insert() {
    806         let mut map = SupersetMap::new();
    807         _ = map.insert(ClosedInterval { min: 0, max: 3 }, ());
    808         _ = map.insert(ClosedInterval { min: 0, max: 3 }, ());
    809         _ = map.insert(ClosedInterval { min: 0, max: 4 }, ());
    810         _ = map.insert(ClosedInterval { min: 1, max: 4 }, ());
    811         _ = map.insert(ClosedInterval { min: 4, max: 6 }, ());
    812         _ = map.insert(ClosedInterval { min: 2, max: 7 }, ());
    813         _ = map.insert(ClosedInterval { min: 10, max: 17 }, ());
    814         let mut keys = map.into_keys();
    815         assert!(
    816             keys.next()
    817                 .is_some_and(|set| set == ClosedInterval { min: 0, max: 4 })
    818         );
    819         assert!(
    820             keys.next()
    821                 .is_some_and(|set| set == ClosedInterval { min: 2, max: 7 })
    822         );
    823         assert!(
    824             keys.next()
    825                 .is_some_and(|set| set == ClosedInterval { min: 10, max: 17 })
    826         );
    827         assert!(keys.next().is_none());
    828         assert!(keys.next().is_none());
    829         assert!(keys.next().is_none());
    830     }
    831     #[test]
    832     fn append() {
    833         let mut map = SupersetMap::new();
    834         _ = map.insert(ClosedInterval { min: 0, max: 3 }, ());
    835         _ = map.insert(ClosedInterval { min: 0, max: 3 }, ());
    836         _ = map.insert(ClosedInterval { min: 0, max: 4 }, ());
    837         _ = map.insert(ClosedInterval { min: 1, max: 4 }, ());
    838         _ = map.insert(ClosedInterval { min: 4, max: 6 }, ());
    839         _ = map.insert(ClosedInterval { min: 2, max: 7 }, ());
    840         _ = map.insert(ClosedInterval { min: 10, max: 17 }, ());
    841         let mut map2 = SupersetMap::new();
    842         _ = map2.insert(ClosedInterval { min: 0, max: 1 }, ());
    843         _ = map2.insert(ClosedInterval { min: 1, max: 14 }, ());
    844         _ = map2.insert(ClosedInterval { min: 11, max: 18 }, ());
    845         map.append(map2);
    846         let mut keys = map.into_keys();
    847         assert!(
    848             keys.next()
    849                 .is_some_and(|set| set == ClosedInterval { min: 0, max: 4 })
    850         );
    851         assert!(
    852             keys.next()
    853                 .is_some_and(|set| set == ClosedInterval { min: 1, max: 14 })
    854         );
    855         assert!(
    856             keys.next()
    857                 .is_some_and(|set| set == ClosedInterval { min: 10, max: 17 })
    858         );
    859         assert!(
    860             keys.next()
    861                 .is_some_and(|set| set == ClosedInterval { min: 11, max: 18 })
    862         );
    863         assert!(keys.next().is_none());
    864         assert!(keys.next().is_none());
    865         assert!(keys.next().is_none());
    866     }
    867     #[test]
    868     fn contains() {
    869         let mut map = SupersetMap::new();
    870         _ = map.insert(ClosedInterval { min: 0, max: 3 }, ());
    871         _ = map.insert(ClosedInterval { min: 0, max: 3 }, ());
    872         _ = map.insert(ClosedInterval { min: 0, max: 4 }, ());
    873         _ = map.insert(ClosedInterval { min: 1, max: 4 }, ());
    874         _ = map.insert(ClosedInterval { min: 4, max: 6 }, ());
    875         _ = map.insert(ClosedInterval { min: 2, max: 7 }, ());
    876         _ = map.insert(ClosedInterval { min: 10, max: 17 }, ());
    877         assert!(map.contains_proper_subset(&ClosedInterval { min: 0, max: 10 }));
    878         assert!(!map.contains_proper_subset(&ClosedInterval { min: 10, max: 17 }));
    879         assert!(!map.contains_proper_subset(&ClosedInterval { min: 210, max: 217 }));
    880         assert!(map.contains_proper_superset(&ClosedInterval { min: 0, max: 1 }));
    881         assert!(!map.contains_proper_superset(&ClosedInterval { min: 10, max: 17 }));
    882         assert!(!map.contains_proper_superset(&ClosedInterval { min: 210, max: 217 }));
    883         assert!(map.contains_subset(&ClosedInterval { min: 0, max: 10 }));
    884         assert!(map.contains_subset(&ClosedInterval { min: 10, max: 17 }));
    885         assert!(!map.contains_subset(&ClosedInterval { min: 210, max: 217 }));
    886         assert!(map.contains_superset(&ClosedInterval { min: 0, max: 1 }));
    887         assert!(map.contains_superset(&ClosedInterval { min: 10, max: 17 }));
    888         assert!(!map.contains_superset(&ClosedInterval { min: 210, max: 217 }));
    889     }
    890     #[test]
    891     fn get() {
    892         let mut map = SupersetMap::new();
    893         _ = map.insert(ClosedInterval { min: 0, max: 3 }, ());
    894         _ = map.insert(ClosedInterval { min: 0, max: 3 }, ());
    895         _ = map.insert(ClosedInterval { min: 0, max: 4 }, ());
    896         _ = map.insert(ClosedInterval { min: 1, max: 4 }, ());
    897         _ = map.insert(ClosedInterval { min: 4, max: 6 }, ());
    898         _ = map.insert(ClosedInterval { min: 2, max: 7 }, ());
    899         _ = map.insert(ClosedInterval { min: 10, max: 17 }, ());
    900         assert!(
    901             map.get_greatest_proper_subset_key_value(&ClosedInterval { min: 0, max: 10 })
    902                 .is_some_and(|info| *info.0 == ClosedInterval { min: 2, max: 7 })
    903         );
    904         assert!(
    905             map.get_greatest_proper_subset_key_value(&ClosedInterval { min: 10, max: 17 })
    906                 .is_none()
    907         );
    908         assert!(
    909             map.get_greatest_proper_subset_key_value(&ClosedInterval { min: 210, max: 217 })
    910                 .is_none()
    911         );
    912         assert!(
    913             map.get_least_proper_superset_key_value(&ClosedInterval { min: 3, max: 4 })
    914                 .is_some_and(|info| *info.0 == ClosedInterval { min: 0, max: 4 })
    915         );
    916         assert!(
    917             map.get_least_proper_superset_key_value(&ClosedInterval { min: 10, max: 17 })
    918                 .is_none()
    919         );
    920         assert!(
    921             map.get_least_proper_superset_key_value(&ClosedInterval { min: 210, max: 217 })
    922                 .is_none()
    923         );
    924         assert!(
    925             map.get_greatest_subset_key_value(&ClosedInterval { min: 0, max: 10 })
    926                 .is_some_and(|info| *info.0 == ClosedInterval { min: 2, max: 7 })
    927         );
    928         assert!(
    929             map.get_greatest_subset_key_value(&ClosedInterval { min: 10, max: 17 })
    930                 .is_some_and(|info| *info.0 == ClosedInterval { min: 10, max: 17 })
    931         );
    932         assert!(
    933             map.get_greatest_subset_key_value(&ClosedInterval { min: 210, max: 217 })
    934                 .is_none()
    935         );
    936         assert!(
    937             map.get_least_superset_key_value(&ClosedInterval { min: 3, max: 4 })
    938                 .is_some_and(|info| *info.0 == ClosedInterval { min: 0, max: 4 })
    939         );
    940         assert!(
    941             map.get_least_superset_key_value(&ClosedInterval { min: 10, max: 17 })
    942                 .is_some_and(|info| *info.0 == ClosedInterval { min: 10, max: 17 })
    943         );
    944         assert!(
    945             map.get_least_superset_key_value(&ClosedInterval { min: 210, max: 217 })
    946                 .is_none()
    947         );
    948     }
    949     #[test]
    950     fn remove() {
    951         let mut map = SupersetMap::new();
    952         _ = map.insert(ClosedInterval { min: 0, max: 3 }, ());
    953         _ = map.insert(ClosedInterval { min: 0, max: 3 }, ());
    954         _ = map.insert(ClosedInterval { min: 0, max: 4 }, ());
    955         _ = map.insert(ClosedInterval { min: 1, max: 4 }, ());
    956         _ = map.insert(ClosedInterval { min: 4, max: 6 }, ());
    957         _ = map.insert(ClosedInterval { min: 2, max: 7 }, ());
    958         _ = map.insert(ClosedInterval { min: 10, max: 17 }, ());
    959         assert!(
    960             map.remove_greatest_proper_subset(&ClosedInterval { min: 0, max: 10 })
    961                 .is_some_and(|info| info.0 == ClosedInterval { min: 2, max: 7 })
    962         );
    963         assert!(
    964             map.remove_greatest_proper_subset(&ClosedInterval { min: 10, max: 17 })
    965                 .is_none()
    966         );
    967         assert!(
    968             map.remove_greatest_proper_subset(&ClosedInterval { min: 210, max: 217 })
    969                 .is_none()
    970         );
    971         assert!(
    972             map.remove_least_proper_superset(&ClosedInterval { min: 3, max: 4 })
    973                 .is_some_and(|info| info.0 == ClosedInterval { min: 0, max: 4 })
    974         );
    975         assert!(
    976             map.remove_least_proper_superset(&ClosedInterval { min: 10, max: 17 })
    977                 .is_none()
    978         );
    979         assert!(
    980             map.remove_least_proper_superset(&ClosedInterval { min: 210, max: 217 })
    981                 .is_none()
    982         );
    983         assert!(
    984             map.remove_greatest_subset(&ClosedInterval { min: 0, max: 10 })
    985                 .is_none()
    986         );
    987         assert!(
    988             map.remove_greatest_subset(&ClosedInterval { min: 10, max: 17 })
    989                 .is_some_and(|info| info.0 == ClosedInterval { min: 10, max: 17 })
    990         );
    991         assert!(
    992             map.remove_greatest_subset(&ClosedInterval { min: 210, max: 217 })
    993                 .is_none()
    994         );
    995         assert!(
    996             map.remove_least_superset(&ClosedInterval { min: 3, max: 4 })
    997                 .is_none()
    998         );
    999         assert!(
   1000             map.remove_least_superset(&ClosedInterval { min: 10, max: 17 })
   1001                 .is_none()
   1002         );
   1003         assert!(
   1004             map.remove_least_superset(&ClosedInterval { min: 210, max: 217 })
   1005                 .is_none()
   1006         );
   1007         let mut map2 = SupersetMap::new();
   1008         _ = map2.insert(ClosedInterval { min: 0, max: 3 }, ());
   1009         _ = map2.insert(ClosedInterval { min: 0, max: 3 }, ());
   1010         _ = map2.insert(ClosedInterval { min: 0, max: 4 }, ());
   1011         _ = map2.insert(ClosedInterval { min: 1, max: 4 }, ());
   1012         _ = map2.insert(ClosedInterval { min: 4, max: 6 }, ());
   1013         _ = map2.insert(ClosedInterval { min: 2, max: 7 }, ());
   1014         _ = map2.insert(ClosedInterval { min: 10, max: 17 }, ());
   1015         assert!(map2.remove_supersets(&ClosedInterval { min: 0, max: 20 }) == 0);
   1016         assert!(map2.remove_subsets(&ClosedInterval { min: 0, max: 1 }) == 0);
   1017         assert!(map2.remove_subsets(&ClosedInterval { min: 0, max: 20 }) == 3);
   1018         _ = map2.insert(ClosedInterval { min: 0, max: 3 }, ());
   1019         _ = map2.insert(ClosedInterval { min: 0, max: 3 }, ());
   1020         _ = map2.insert(ClosedInterval { min: 0, max: 4 }, ());
   1021         _ = map2.insert(ClosedInterval { min: 1, max: 4 }, ());
   1022         _ = map2.insert(ClosedInterval { min: 4, max: 6 }, ());
   1023         _ = map2.insert(ClosedInterval { min: 2, max: 7 }, ());
   1024         _ = map2.insert(ClosedInterval { min: 10, max: 17 }, ());
   1025         assert!(map2.remove_supersets(&ClosedInterval { min: 3, max: 4 }) == 2);
   1026     }
   1027 }