const_sized_bit_set 0.5.0

Bitsets of all sizes an extensive array of associated functions.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
use core::iter::FusedIterator;
use crate::prelude::*;

pub trait BitSet: Sized {
    type Inner;

    const EMPTY: Self;
    ///Returns the number of set bits in the set.
    fn count(&self) -> u32;

    fn into_inner(self) -> Self::Inner;
    fn from_inner(inner: Self::Inner) -> Self;

    fn from_first_n(n: u32) -> Self;

    fn is_empty(&self) -> bool;

    fn clear(&mut self);

    fn contains(&self, element: SetElement) -> bool;

    #[doc(alias = "min")]
    fn first(&self) -> Option<SetElement>;

    #[doc(alias = "max")]
    fn last(&self) -> Option<SetElement>;

    fn pop(&mut self) -> Option<SetElement>;

    fn pop_last(&mut self) -> Option<SetElement>;

    fn iter(
        &self,
    ) -> impl Clone + FusedIterator<Item = SetElement> + DoubleEndedIterator + ExactSizeIterator + CollectIntoBitSet<Self>;

    /// Sets the `element` to `bit`.
    /// Returns whether the element was changed
    fn set_bit(&mut self, element: SetElement, bit: bool) -> bool {
        if bit {
            self.insert(element)
        } else {
            self.remove(element)
        }
    }
    #[must_use]
    fn with_bit_set(&self, element: SetElement, bit: bool) -> Self
    where
        Self: Clone,
    {
        let mut s = self.clone();
        s.set_bit(element, bit);
        s
    }

    /// Insert an element into the set
    /// Returns whether the element was inserted (it was not already present)
    fn insert(&mut self, element: SetElement) -> bool;

    /// Toggle the presence of an element.
    /// Returns whether the element is now present.
    fn toggle(&mut self, element: SetElement) -> bool;

    #[must_use]
    fn with_inserted(&self, element: SetElement) -> Self
    where
        Self: Clone,
    {
        let mut s = self.clone();
        s.insert(element);
        s
    }

    /// Remove an element from the set
    /// Returns whether the element was removed (was previously present)
    fn remove(&mut self, element: SetElement) -> bool;

    #[must_use]
    fn with_removed(&self, element: SetElement) -> Self
    where
        Self: Clone,
    {
        let mut s = self.clone();
        s.remove(element);
        s
    }

    fn swap_bits(&mut self, i: u32, j: u32);

    #[must_use]
    fn with_bits_swapped(&self, i: u32, j: u32) -> Self
    where
        Self: Clone,
    {
        let mut s = self.clone();
        s.swap_bits(i, j);
        s
    }

    fn is_subset(&self, rhs: &Self) -> bool;
    fn is_superset(&self, rhs: &Self) -> bool {
        rhs.is_subset(self)
    }
    fn overlaps(&self, rhs: &Self) -> bool;

    fn intersect_with(&mut self, rhs: &Self);

    #[must_use]
    fn with_intersect(&self, rhs: &Self) -> Self
    where
        Self: Clone,
    {
        let mut s = self.clone();
        s.intersect_with(rhs);
        s
    }

    fn union_with(&mut self, rhs: &Self);
    #[must_use]
    fn with_union(&self, rhs: &Self) -> Self
    where
        Self: Clone,
    {
        let mut s = self.clone();
        s.union_with(rhs);
        s
    }

    fn except_with(&mut self, rhs: &Self);

    #[must_use]
    fn with_except(&self, rhs: &Self) -> Self
    where
        Self: Clone,
    {
        let mut s = self.clone();
        s.except_with(rhs);
        s
    }

    ///Changes this set to contain only the elements that are either currently present or present in `rhs` but not both.
    fn symmetric_difference_with(&mut self, rhs: &Self);

    #[must_use]
    fn with_symmetric_difference(&self, rhs: &Self) -> Self
    where
        Self: Clone,
    {
        let mut s = self.clone();
        s.symmetric_difference_with(rhs);
        s
    }

    /// Return the set of minimal members according to a function
    #[must_use]
    fn min_set_by_key<K: Ord>(&self, f: impl Fn(SetElement) -> K) -> Self {
        let mut result_set = Self::EMPTY;
        let mut iter = self.iter();

        let Some(first) = iter.next() else {
            return result_set;
        };
        let mut min = f(first);
        result_set.insert(first);

        for next in iter {
            let k = f(next);
            match k.cmp(&min) {
                core::cmp::Ordering::Less => {
                    result_set = Self::EMPTY;
                    result_set.insert(next);
                    min = k;
                }
                core::cmp::Ordering::Equal => {
                    result_set.insert(next);
                }
                core::cmp::Ordering::Greater => {}
            }
        }

        result_set
    }

    /// Returns the n+1th element present in the set, if there are at least n + 1 elements
    /// To return the first element, use n == 0
    #[must_use]
    fn nth(&self, n: u32) -> Option<SetElement>;

    /// Returns the number of elements less than `element` in the set
    /// Returns the same result regardless of whether `element` is present
    #[must_use]
    fn count_lesser_elements(&self, element: SetElement) -> u32;

    /// Returns the number of elements greater than `element` in the set
    /// Returns the same result regardless of whether `element` is present
    #[must_use]
    fn count_greater_elements(&self, element: SetElement) -> u32;

    /// Return the smallest element greater than `index`
    /// Will return the same regardless of whether `element` is present
    #[must_use]
    fn smallest_element_greater_than(&self, index: SetElement) -> Option<SetElement>;

    /// Return the smallest element less than `index`
    /// Will return the same regardless of whether `element` is present
    #[must_use]
    fn largest_element_less_than(&self, index: SetElement) -> Option<SetElement>;

    /// Retains only the elements specified by the predicate.     
    fn retain<F>(&mut self, f: F)
    where
        F: FnMut(&SetElement) -> bool;

    #[must_use]
    fn iter_subsets(
        self,
        subset_size: u32,
    ) -> impl ExactSizeIterator<Item = Self> + Clone + core::iter::FusedIterator
    where
        Self: Clone,
    {
        crate::subset_iter::SubsetIter::new(self, subset_size)
    }

    #[must_use]
    fn count_subsets(&self, subset_size: u32) -> u32 {
        crate::n_choose_k::NChooseK::new(self.count(), subset_size).value()
    }

    #[must_use]
    fn index_of_subset(&self, subset: &Self) -> u32 {
        let n_c_k = crate::n_choose_k::NChooseK::new(self.count(), subset.count());

        let Some(mut n_c_k) = n_c_k.try_decrement_n() else {
            return 0;
        };

        let mut total = 0;
        let mut iter = self.iter();
        while let Some(index) = iter.next_back() {
            if subset.contains(index) {
                total += n_c_k.value();
                match n_c_k.try_decrement_k() {
                    Some(r) => n_c_k = r,
                    None => return total,
                }
            }
            match n_c_k.try_decrement_n() {
                Some(r) => n_c_k = r,
                None => return total,
            }
        }

        total
    }

    #[must_use]
    fn get_subset(&self, subset_size: u32, index: u32) -> Self {
        let n_c_k = crate::n_choose_k::NChooseK::new(self.count(), subset_size);

        // The rest of this algorithm calculates the the subsets in reverse order (i.e. index 0 is the largest subset)
        // So reverse the order here to account for that
        let mut index = n_c_k.value() - (index + 1 % n_c_k.value());
        let mut new_set = Self::EMPTY;

        let Some(mut n_c_k) = n_c_k.try_decrement_k().and_then(|x| x.try_decrement_n()) else {
            return new_set;
        };

        let mut iter = self.iter();

        while let Some(next) = iter.next_back() {
            if let Some(new_index) = index.checked_sub(n_c_k.value()) {
                index = new_index;
            } else {
                new_set.set_bit(next, true);
                match n_c_k.try_decrement_k() {
                    Some(r) => n_c_k = r,
                    None => return new_set,
                }
            }
            if let Some(r) = n_c_k.try_decrement_n() {
                n_c_k = r;
            } else {
                iter.collect_into_bit_set(&mut new_set);

                return new_set;
            }
        }

        new_set
    }

    ///Returns the number of ones at the beginning of the set
    /// See `FiniteBitSet` for `trailing_zeros`, `leading_ones` and `leading_zeros`
    fn trailing_ones(&self) -> u32;

    /// Equivalent to >>=
    /// Reduce the value of every element in the set by n.
    /// Elements no longer in range are removed.
    fn shift_right(&mut self, n: SetElement);

    /// Equivalent to <<=
    /// Increase the value of every element in the set by n.
    /// For finite sets, elements no longer in range are removed.
    fn shift_left(&mut self, n: SetElement);
}

macro_rules! impl_bit_set_trait_methods {
    () => {
        fn is_empty(&self) -> bool {
            self.is_empty_const()
        }

        fn count(&self) -> u32 {
            self.count_const()
        }

        fn clear(&mut self) {
            self.clear_const()
        }

        fn into_inner(self) -> Self::Inner {
            self.into_inner_const()
        }

        fn from_inner(inner: Self::Inner) -> Self {
            Self::from_inner_const(inner)
        }

        fn from_first_n(n: u32) -> Self {
            Self::from_first_n_const(n)
        }

        fn contains(&self, element: SetElement) -> bool {
            self.contains_const(element)
        }

        fn first(&self) -> Option<SetElement> {
            self.first_const()
        }

        fn last(&self) -> Option<SetElement> {
            self.last_const()
        }

        fn pop(&mut self) -> Option<SetElement> {
            self.pop_const()
        }

        fn pop_last(&mut self) -> Option<SetElement> {
            self.pop_last_const()
        }

        fn insert(&mut self, element: SetElement) -> bool {
            self.insert_const(element)
        }

        fn remove(&mut self, element: SetElement) -> bool {
            self.remove_const(element)
        }

        fn toggle(&mut self, element: SetElement) -> bool {
            self.toggle_const(element)
        }

        fn swap_bits(&mut self, i: u32, j: u32) {
            self.swap_bits_const(i, j);
        }

        fn is_subset(&self, rhs: &Self) -> bool {
            self.is_subset_const(rhs)
        }

        fn overlaps(&self, rhs: &Self) -> bool {
            self.overlaps_const(rhs)
        }

        fn intersect_with(&mut self, rhs: &Self) {
            self.intersect_with_const(rhs);
        }

        fn union_with(&mut self, rhs: &Self) {
            self.union_with_const(rhs)
        }

        fn except_with(&mut self, rhs: &Self) {
            self.except_with_const(rhs)
        }

        fn symmetric_difference_with(&mut self, rhs: &Self) {
            self.symmetric_difference_with_const(rhs);
        }

        fn nth(&self, n: u32) -> Option<SetElement> {
            self.nth_const(n)
        }

        fn count_lesser_elements(&self, element: SetElement) -> u32 {
            self.count_lesser_elements_const(element)
        }

        fn count_greater_elements(&self, element: SetElement) -> u32 {
            self.count_greater_elements_const(element)
        }

        fn smallest_element_greater_than(&self, index: SetElement) -> Option<SetElement> {
            self.smallest_element_greater_than_const(index)
        }

        fn largest_element_less_than(&self, index: SetElement) -> Option<SetElement> {
            self.largest_element_less_than_const(index)
        }

        fn trailing_ones(&self) -> u32 {
            self.trailing_ones_const()
        }

        fn iter(
            &self,
        ) -> impl Clone + FusedIterator<Item = SetElement> + DoubleEndedIterator + ExactSizeIterator + CollectIntoBitSet<Self>
        {
            self.iter_const()
        }

        fn shift_right(&mut self, n: SetElement)
        {
            self.shift_right_const(n)
        }

        fn shift_left(&mut self, n: SetElement)
        {
            self.shift_left_const(n)
        }        
    };
}

macro_rules! impl_bit_set_trait {
    ($name:ident, $inner: ty) => {
        impl BitSet for $name {
            type Inner = $inner;
            const EMPTY: Self = Self::EMPTY;

            impl_bit_set_trait_methods!();

            fn retain<F>(&mut self, mut f: F)
            where
                F: FnMut(&SetElement) -> bool,
            {
                for x in self.clone().iter() {
                    if !f(&x) {
                        self.remove(x);
                    }
                }
            }
        }
    };
}

impl_bit_set_trait!(BitSet8, u8);
impl_bit_set_trait!(BitSet16, u16);
impl_bit_set_trait!(BitSet32, u32);
impl_bit_set_trait!(BitSet64, u64);
impl_bit_set_trait!(BitSet128, u128);

impl<const WORDS: usize> BitSet for crate::prelude::BitSetArray<WORDS> {
    type Inner = [u64; WORDS];
    const EMPTY: Self = Self::EMPTY;

    impl_bit_set_trait_methods!();
    #[allow(clippy::cast_possible_truncation)]
    fn retain<F>(&mut self, mut f: F)
    where
        F: FnMut(&SetElement) -> bool,
    {
        let mut word_index = 0;
        while let Some(word) = self.0.get_mut(word_index) {
            let w = *word;
            let offset = word_index as u32 * u64::BITS;
            for element_index in BitSet64::from_inner_const(w).iter_const() {
                if !f(&(element_index + offset)) {
                    crate::mutate_inner(word, |w| w.remove_const(element_index));
                }
            }
            word_index += 1;
        }
    }
}