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
#![no_std]
#![feature(adt_const_params)]
#![feature(generic_const_exprs)]
#![feature(array_methods)]
#![allow(incomplete_features)]

//! ```rust
//! # #![feature(variant_count)]
//! # use std::error::Error;
//! #
//! # extern crate staticbitset;
//! # fn main() -> Result<(), Box<Error>> {
//! use staticbitset::StaticBitSet;
//! #[repr(usize)]
//! enum Hats {
//!     Cap,
//!     Top,
//!     Bowler,
//!     Beret,
//!     Fez,
//! }
//! use Hats::*;
//! use core::mem;
//!
//! type HatBitSet = StaticBitSet::<{mem::variant_count::<Hats>()}>;
//! assert_eq!(4, mem::size_of::<HatBitSet>());
//!
//! assert_eq!(8, mem::size_of::< StaticBitSet::<64> >());
//! assert_eq!(4, mem::size_of::< StaticBitSet::<32> >());
//! assert_eq!(4, mem::size_of::< StaticBitSet::<31> >());
//!
//! let mut x = StaticBitSet::<64>::default();
//! assert!(!x.contains(Fez as usize));
//!
//! x.insert(Fez as usize);
//! assert!(x.contains(Fez as usize));
//!
//! x.clear();
//! assert!(!x.contains(Fez as usize));
//!
//! x.set(Fez as usize, true);
//! assert!(x.contains(Fez as usize));
//!
//! x.set(Fez as usize, false);
//! assert!(!x.contains(Fez as usize));
//! assert!(!x.contains(Bowler as usize));
//!
//! for hat in x.ones().into_iter() {
//!    println!("Hat index: {}", hat);
//! }
//! #     Ok(())
//! # }
//! ```

// TODO: would 'usize' be a better assumption for an optimal
// (general register-sized?) block?  Or maybe these should be
// target specific?
pub type BlockElt = u32;
pub const BLOCK_SIZE_BITS: usize = core::mem::size_of::<BlockElt>() * 8;
pub const fn bits_to_blocks<const N: usize>() -> usize {
    (N + BLOCK_SIZE_BITS - 1) / BLOCK_SIZE_BITS
}
pub type BlockElts<const N: usize> = [BlockElt; bits_to_blocks::<N>()];

#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub struct StaticBitSet<const N: usize>
where
    [(); bits_to_blocks::<N>()]:,
{
    bit_blocks: BlockElts<N>,
}

impl<const N: usize> Default for StaticBitSet<N>
where
    [(); bits_to_blocks::<N>()]:,
{
    fn default() -> Self {
        Self {
            bit_blocks: [0; bits_to_blocks::<N>()],
        }
    }
}

struct BitBlockIdx {
    pub block: usize,
    pub bit: usize,
}
#[inline]
const fn index(bit: usize) -> BitBlockIdx {
    BitBlockIdx {
        block: bit / BLOCK_SIZE_BITS,
        bit: bit % BLOCK_SIZE_BITS,
    }
}

impl<const N: usize> StaticBitSet<N>
where
    [(); bits_to_blocks::<N>()]:,
{
    /// Clears the set, removing all values.
    pub fn clear(&mut self) {
        for block in self.bit_blocks.as_mut_slice() {
            *block = BlockElt::default();
        }
    }

    pub fn remove(&mut self, bit: usize) {
        self.set(bit, false);
    }

    /// Inserts `bit` into the set.
    ///
    /// # Panics
    /// Panics if 'bit' is beyond the bounds of the `StaticBitSet`.
    pub fn insert(&mut self, bit: usize) {
        self.set(bit, true);
    }

    #[inline]
    pub fn set(&mut self, bit: usize, enabled: bool) {
        let index = index(bit);
        if enabled {
            self.blocks_mut_slice()[index.block] |= 1 << index.bit;
        } else {
            self.blocks_mut_slice()[index.block] &= !(1 << index.bit);
        }
    }

    #[inline]
    pub fn contains(&self, bit: usize) -> bool {
        let index = index(bit);

        (self.blocks_slice()[index.block] & (1 << index.bit)) != 0
    }

    #[inline]
    fn blocks_slice(&self) -> &[BlockElt] {
        self.bit_blocks.as_slice()
    }

    #[inline]
    fn blocks_mut_slice(&mut self) -> &mut [BlockElt] {
        self.bit_blocks.as_mut_slice()
    }

    #[inline]
    pub fn ones(&self) -> OnesIter {
        OnesIter {
            block_index: 0,
            bit_index: 0,
            blocks: self.blocks_slice(),
        }
    }

    /// Returns the number of elements in the set.
    pub fn count_ones(&self) -> BlockElt {
        self.blocks_slice().iter().map(|x| x.count_ones()).sum()
    }

    /// Returns the number of elements missing from the set.
    pub fn count_zeros(&self) -> BlockElt {
        self.blocks_slice().iter().map(|x| x.count_zeros()).sum()
    }

    /// Returns true if the set contains no elements.
    pub fn is_empty(&self) -> bool {
        self.blocks_slice().iter().all(|block| *block == 0)
    }

    /// Returns `true` if the set is a subset of another, i.e. `other`
    /// contains at least all the values in `self`.
    pub fn is_subset(&self, other: &Self) -> bool {
        let self_slice = self.blocks_slice();
        let other_slice = other.blocks_slice();
        self_slice
            .iter()
            .zip(other_slice)
            .all(|(this, that)| *this & *that == *this)
    }

    /// Returns `true` if the set is a subset of another, i.e. `self`
    /// contains at least all the values in `other`.
    pub fn is_superset(&self, other: &Self) -> bool {
        other.is_subset(self)
    }

    /// Returns `true` if `self` has no elements in common with other. This is
    /// equivalent to checking for an empty intersection.
    pub fn is_disjoint(&self, other: &Self) -> bool {
        let self_slice = self.blocks_slice();
        let other_slice = other.blocks_slice();
        self_slice
            .iter()
            .zip(other_slice)
            .all(|(x, y)| *x & *y == 0)
    }

    /// Populates the union, i.e. all the values in `self`
    /// or `other`, without duplicates.
    /// ```rust
    /// # use std::error::Error;
    /// #
    /// # extern crate staticbitset;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use staticbitset::StaticBitSet;
    /// let mut a = StaticBitSet::<64>::default();
    /// let mut b = StaticBitSet::<64>::default();
    /// let mut c = StaticBitSet::<64>::default();
    /// a.insert(3);
    /// a.insert(2);
    /// b.insert(1);
    /// b.insert(4);
    /// a.union(&b, &mut c);
    /// assert_eq!(c.ones().collect::<Vec<usize>>(), [1,2,3,4]);
    /// #     Ok(())
    /// # }
    /// ```
    pub fn union(&self, other: &Self, union: &mut Self) {
        let self_slice = self.blocks_slice();
        let other_slice = other.blocks_slice();
        let union_slice = union.blocks_mut_slice();

        for (i, (x, y)) in self_slice.iter().zip(other_slice).enumerate() {
            union_slice[i] = *x | *y;
        }
    }
}

pub struct OnesIter<'a> {
    bit_index: usize,
    block_index: usize,
    blocks: &'a [BlockElt],
}
impl<'a> Iterator for OnesIter<'a> {
    type Item = usize;

    fn next(&mut self) -> Option<Self::Item> {
        for block in self.blocks[self.block_index..].iter() {
            let block_bit_index = self.block_index * BLOCK_SIZE_BITS;
            for j in self.bit_index..BLOCK_SIZE_BITS {
                self.bit_index = j;
                if (block >> j & 1) != 0 {
                    let absolute_bit_index = block_bit_index + j;
                    self.bit_index += 1;
                    return Some(absolute_bit_index);
                }
            }
            self.bit_index = 0;
            self.block_index += 1;
        }

        None
    }
}

#[cfg(test)]
#[macro_use]
extern crate std;
mod tests {
    #[cfg(test)]
    use crate::StaticBitSet;

    #[test]
    fn test_macro() {
        let foo = StaticBitSet::<1>::default();
        assert_eq!(foo.bit_blocks.len(), 1);

        let bar = StaticBitSet::<256>::default();
        assert_eq!(bar.bit_blocks.len(), 8);

        let baz = StaticBitSet::<257>::default();
        assert_eq!(baz.bit_blocks.len(), 9);

        use crate::BlockElt;
        use core::mem::size_of;
        type B64 = StaticBitSet<64>;
        assert_eq!(size_of::<B64>(), 2 * size_of::<BlockElt>());
    }

    #[test]
    fn test_count() {
        let mut x = StaticBitSet::<256>::default();
        assert_eq!(x.count_ones(), 0);
        assert_eq!(x.count_zeros(), 256);
        x.clear();
        assert_eq!(x.count_ones(), 0);
        x.insert(3);
        assert_eq!(x.count_ones(), 1);

        let mut y = x;
        assert_eq!(y.count_ones(), 1);
        y.clear();
        assert_eq!(y.count_ones(), 0);

        let mut z = x;
        assert_eq!(z.count_ones(), 1);
        assert_eq!(z.count_zeros(), 255);
        assert_eq!(x.count_zeros(), 255);
        z.set(3, false);
        assert_eq!(y.count_ones(), 0);

        let mut w = StaticBitSet::<256>::default();
        assert_eq!(w.count_ones(), 0);
        w.set(15, true);
        assert_eq!(w.count_ones(), 1);
        w.set(127, true);
        assert_eq!(w.count_ones(), 2);
        w.set(17, true);
        assert_eq!(w.count_ones(), 3);
        w.set(19, true);
        assert_eq!(w.count_ones(), 4);
        w.set(243, true);
        assert_eq!(w.count_ones(), 5);

        for i in 0..12 {
            w.insert(i);
        }
        assert_eq!(w.count_ones(), 17);

        w.clear();
        assert_eq!(w.count_ones(), 0);

        w = y;
        assert_eq!(w.count_ones(), 0);
        w = x;
        assert_eq!(w.count_ones(), 1);
    }

    #[test]
    fn test_contains() {
        let mut x = StaticBitSet::<256>::default();
        let (low, high) = (68, 98);
        for i in 0..256 {
            assert!(!x.contains(i));
        }

        for i in low..high {
            x.insert(i);
        }

        for i in low..high {
            assert!(x.contains(i));
        }
        for i in 0..low {
            assert!(!x.contains(i));
        }
        for i in high..256 {
            assert!(!x.contains(i));
        }
    }

    #[test]
    fn test_clear_set() {
        let mut x = StaticBitSet::<64>::default();
        assert!(!x.contains(3));
        x.clear();
        assert!(!x.contains(3));
        x.set(3, true);
        assert!(x.contains(3));
        assert!(x.contains(3));
        x.set(3, false);
        assert!(!x.contains(3));
        assert!(!x.contains(3));

        let mut y = x;
        assert!(!y.contains(3));
        y.clear();
        assert!(!x.contains(3));
        assert!(!y.contains(3));
    }

    #[test]
    fn test_logic() {
        let mut x = StaticBitSet::<256>::default();
        assert!(x.is_empty());
        x.insert(3);
        assert!(!x.is_empty());
        let z = x;
        assert_eq!(x, z);
        assert_eq!(x.contains(3), true);
        assert_eq!(z.contains(3), true);
        assert!(!x.is_disjoint(&z));
        assert!(!z.is_disjoint(&x));
        assert!(z.is_subset(&x));
        assert!(x.is_subset(&z));
        assert!(z.is_superset(&x));
        assert!(x.is_superset(&z));

        let mut y = StaticBitSet::<256>::default();
        for i in 0..12 {
            y.insert(i);
        }
        y.insert(99);

        assert!(!x.is_superset(&y));
        assert!(x.is_subset(&y));
        assert!(y.is_superset(&x));
        assert!(!y.is_subset(&x));

        y.remove(3);

        assert!(x.is_disjoint(&y));
        assert!(y.is_disjoint(&x));
        assert!(!x.is_subset(&y));
        assert!(!y.is_subset(&x));
        assert!(!x.is_superset(&y));
        assert!(!y.is_superset(&x));

        assert!(x.is_superset(&x));
        assert!(y.is_superset(&y));

        let mut w = StaticBitSet::<256>::default();
        x.union(&y, &mut w);
        assert_ne!(x, y);
        assert!(w.is_superset(&x));
        assert!(w.is_superset(&y));
        assert!(x.is_subset(&w));
        assert!(y.is_subset(&w));
        assert_ne!(w, x);
        assert_ne!(w, y);

        assert!(!z.is_empty());
        assert!(!w.is_empty());
        assert!(!x.is_empty());
        assert!(!y.is_empty());
    }

    #[test]
    #[should_panic]
    fn test_range_panics() {
        let mut x = StaticBitSet::<33>::default();
        x.insert(64);
    }

    #[test]
    fn test_range_valid() {
        let mut x = StaticBitSet::<33>::default();
        x.insert(0);
        x.insert(34);
        assert_eq!(x.count_ones(), 2);
    }

    #[test]
    fn test_ones() {
        let mut x = StaticBitSet::<256>::default();

        assert_eq!(x.ones().collect::<Vec<usize>>(), vec![]);

        for i in 60..70 {
            x.insert(i);
        }
        x.remove(65);

        use std::vec::Vec;
        let y: Vec<usize> = vec![60, 61, 62, 63, 64, 66, 67, 68, 69];
        assert_eq!(x.ones().collect::<Vec<usize>>(), y);
    }
}