light_bitmap 0.1.0

A minimal, fixed-size bitmap library written in pure Rust.
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
use core::array::from_fn;
use core::fmt::{Debug, Formatter};
use core::iter::{FusedIterator, Iterator};
use core::ops::{
    BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Not, Range, Shl, ShlAssign,
    Shr, ShrAssign,
};

/// Computes the number of buckets needed to store `bit_count` bits.
///
/// It's recommended to inline this call as a const expression into the type
/// annotation generics to avoid unnecessary panics.
///
/// # Examples
/// ```
/// use light_bitmap::bucket_count;
///
/// assert_eq!(bucket_count(9), 2);
/// assert_eq!(bucket_count(16), 2);
/// assert_eq!(bucket_count(17), 3);
/// ```
pub const fn bucket_count(bit_count: usize) -> usize {
    bit_count.div_ceil(8)
}

#[allow(clippy::no_effect)]
#[allow(clippy::unnecessary_operation)]
pub(crate) const fn compile_assert_const_params(bit_count: usize, buckets: usize) {
    // This will cause a compile-time error if bit_count == 0
    ["BIT_COUNT must be greater than zero."][(bit_count == 0) as usize];
    // This will cause a compile-time error if buckets != bucket_count(bit_count)
    ["BUCKET_COUNT must match bucket_count(BIT_COUNT)."]
        [(bucket_count(bit_count) != buckets) as usize];
}

pub(crate) fn runtime_assert_const_params(bit_count: usize, buckets: usize) {
    assert_ne!(bit_count, 0, "BIT_COUNT must be greater than zero.");
    assert_eq!(
        bucket_count(bit_count),
        buckets,
        "BUCKET_COUNT must match bucket_count(BIT_COUNT)."
    );
}

pub(crate) const fn ones_mask(start_bit: usize, width: usize) -> u8 {
    if width >= 8 {
        // shift would be undefined / panic on u8
        !0u8
    } else {
        // if `1u8 << shift_amount` == 0 wrap around
        (1u8 << width).wrapping_sub(1) << start_bit
    }
}

/// The main type that stores the information.
///
/// `BIT_COUNT` is the number of usable bits.
/// `BUCKET_COUNT` is the number of internal buckets needed and should only be
/// set via const expression with [`bucket_count`] to avoid unnecessary panics
/// (see [`new`]).
///
/// Internally stores bits in an array of `u8`.
///
/// [`new`]: BitMap::new
#[derive(PartialEq, Eq, Hash, Clone, Copy)]
pub struct BitMap<const BIT_COUNT: usize, const BUCKET_COUNT: usize>(pub(crate) [u8; BUCKET_COUNT]);

impl<const BIT_COUNT: usize, const BUCKET_COUNT: usize> BitMap<BIT_COUNT, BUCKET_COUNT> {
    /// Creates a new bitmap with all bits unset.
    ///
    /// # Panics
    /// Panics if `BIT_COUNT == 0` or `BUCKET_COUNT != bucket_count(BIT_COUNT)`.
    ///
    /// # Examples
    /// ```
    /// use light_bitmap::{BitMap, bucket_count};
    ///
    /// let bitmap = BitMap::<16, { bucket_count(16) }>::new();
    /// assert_eq!(bitmap.popcount(), 0);
    /// ```
    pub fn new() -> Self {
        runtime_assert_const_params(BIT_COUNT, BUCKET_COUNT);
        Self([0u8; BUCKET_COUNT])
    }

    /// Creates a new `const` bitmap with all bits unset.
    ///
    /// Equivalent to [`new`], but callable in compile-time contexts such as
    /// const initialization.
    ///
    /// # Compiler Errors
    /// Prevents compilation if either `BIT_COUNT == 0` or `BUCKET_COUNT !=
    /// bucket_count(bit_count)` with an unintuitive message like `evaluation of
    /// constant value failed` and `index out of bounds: the length is 1 but the
    /// index is 1`.
    ///
    /// # Examples
    /// ```
    /// use light_bitmap::{BitMap, bucket_count};
    ///
    /// const EMPTY: BitMap<8, { bucket_count(8) }> = BitMap::const_empty();
    /// assert_eq!(EMPTY.popcount(), 0);
    /// ```
    ///
    /// [`new`]: BitMap::new
    pub const fn const_empty() -> Self {
        compile_assert_const_params(BIT_COUNT, BUCKET_COUNT);
        Self([0u8; BUCKET_COUNT])
    }

    /// Creates a new bitmap with all bits set.
    ///
    /// # Panics
    /// Panics if `BIT_COUNT == 0` or `BUCKET_COUNT != bucket_count(BIT_COUNT)`.
    ///
    /// # Examples
    /// ```
    /// use light_bitmap::{BitMap, bucket_count};
    ///
    /// let bitmap = BitMap::<10, { bucket_count(10) }>::with_all_set();
    /// assert_eq!(bitmap.popcount(), 10);
    /// ```
    #[inline]
    pub fn with_all_set() -> Self {
        runtime_assert_const_params(BIT_COUNT, BUCKET_COUNT);
        let mut bm = Self([!0u8; BUCKET_COUNT]);
        bm.clean_unused_bits();
        bm
    }

    /// Creates a new `const` bitmap with all bits set.
    ///
    /// Equivalent to [`with_all_set`], but callable in compile-time contexts
    /// such as const initialization.
    ///
    /// # Compiler Errors
    /// Prevents compilation if either `BIT_COUNT == 0` or `BUCKET_COUNT !=
    /// bucket_count(bit_count)` with an unintuitive message like `evaluation of
    /// constant value failed` and `index out of bounds: the length is 1 but the
    /// index is 1`.
    ///
    /// # Examples
    /// ```
    /// use light_bitmap::{BitMap, bucket_count};
    ///
    /// const FULL: BitMap<10, { bucket_count(10) }> = BitMap::const_full();
    /// assert_eq!(FULL.popcount(), 10);
    /// ```
    ///
    /// [`with_all_set`]: BitMap::with_all_set
    pub const fn const_full() -> Self {
        compile_assert_const_params(BIT_COUNT, BUCKET_COUNT);
        let mut bm = Self([!0u8; BUCKET_COUNT]);
        bm.clean_unused_bits();
        bm
    }

    /// Constructs a bitmap from a boolean slice, where `true` means set.
    ///
    /// # Panics
    /// Panics if the slice length doesn't match `BIT_COUNT`, if `BIT_COUNT == 0`
    /// or if `BUCKET_COUNT != bucket_count(BIT_COUNT)`.
    ///
    /// # Examples
    /// ```
    /// use light_bitmap::{BitMap, bucket_count};
    ///
    /// let bitmap = BitMap::<4, { bucket_count(4) }>::from_slice(&[true, false, true, false]);
    /// assert_eq!(bitmap.popcount(), 2);
    /// ```
    #[inline]
    pub fn from_slice(bits: &[bool]) -> Self {
        runtime_assert_const_params(BIT_COUNT, BUCKET_COUNT);
        assert_eq!(bits.len(), BIT_COUNT);
        let mut bm = Self([0u8; BUCKET_COUNT]);
        for (idx, bit) in bits.iter().enumerate() {
            if *bit {
                bm.set(idx)
            }
        }
        bm
    }

    /// Constructs a bitmap by setting only the indices provided in the iterator.
    ///
    /// All unspecified indices are left unset.
    ///
    /// # Panics
    /// Panics if any index is out of bounds (i.e., `>= BIT_COUNT`), if
    /// `BIT_COUNT == 0` or if `BUCKET_COUNT != bucket_count(BIT_COUNT)`.
    ///
    /// # Examples
    /// ```
    /// use light_bitmap::{BitMap, bucket_count};
    ///
    /// let bitmap = BitMap::<5, { bucket_count(5) }>::from_ones_iter([0, 2, 4]);
    /// assert!(bitmap.is_set(0));
    /// assert!(!bitmap.is_set(1));
    /// assert_eq!(bitmap.popcount(), 3);
    /// ```
    pub fn from_ones_iter<I: IntoIterator<Item = usize>>(iter: I) -> Self {
        runtime_assert_const_params(BIT_COUNT, BUCKET_COUNT);
        let mut bitmap = Self::new();
        for idx in iter {
            assert!(idx < BIT_COUNT, "Bit index {idx} out of bounds");
            bitmap.set(idx);
        }
        bitmap
    }

    /// Sets the bit at the given index.
    ///
    /// # Panics
    /// Panics if the index is out of bounds (i.e., `>= BIT_COUNT`).
    ///
    /// # Examples
    /// ```
    /// use light_bitmap::{BitMap, bucket_count};
    ///
    /// let mut bm = BitMap::<8, { bucket_count(8) }>::new();
    /// assert!(!bm.is_set(3));
    /// bm.set(3);
    /// assert!(bm.is_set(3));
    /// ```
    #[inline]
    pub fn set(&mut self, idx: usize) {
        assert!(idx < BIT_COUNT, "Bit index {idx} out of bounds");
        let (group_idx, item_idx) = Self::idxs(idx);
        self.0[group_idx] |= 1 << item_idx;
    }

    /// Sets all bits in the given range.
    ///
    /// # Panics
    /// Panics if `range.start >= BIT_COUNT` or `range.end > BIT_COUNT`.
    ///
    /// # Examples
    /// ```
    /// use light_bitmap::{BitMap, bucket_count};
    ///
    /// let mut bm = BitMap::<8, { bucket_count(8) }>::new();
    /// bm.set_range(2..6);
    /// assert!(bm.is_set(2));
    /// assert!(bm.is_set(5));
    /// assert!(!bm.is_set(6));
    /// ```
    pub fn set_range(&mut self, range: Range<usize>) {
        assert!(
            range.start < BIT_COUNT,
            "Range start {} out of bounds",
            range.start
        );
        assert!(
            range.end <= BIT_COUNT,
            "Range end {} out of bounds",
            range.end
        );

        if range.start >= range.end {
            return;
        }

        let (start_byte, start_bit) = Self::idxs(range.start);
        let (end_byte, end_bit) = Self::idxs(range.end - 1);

        // all within one byte
        if start_byte == end_byte {
            let width = end_bit - start_bit + 1;
            let mask = ones_mask(start_bit, width);
            self.0[start_byte] |= mask;
            return;
        }

        // set bits in first byte
        let first_mask = !0u8 << start_bit;
        self.0[start_byte] |= first_mask;

        // set full bytes in between
        for byte in &mut self.0[start_byte + 1..end_byte] {
            *byte = !0;
        }

        // set bits in last byte
        let width = end_bit + 1;
        let last_mask = ones_mask(0, width);
        self.0[end_byte] |= last_mask;
    }

    /// Unsets the bit at the given index.
    ///
    /// # Panics
    /// Panics if `idx >= BIT_COUNT`.
    ///
    /// # Examples
    /// ```
    /// use light_bitmap::{BitMap, bucket_count};
    ///
    /// let mut bm = BitMap::<8, { bucket_count(8) }>::with_all_set();
    /// assert!(bm.is_set(3));
    /// bm.unset(3);
    /// assert!(!bm.is_set(3));
    /// ```
    #[inline]
    pub fn unset(&mut self, idx: usize) {
        assert!(idx < BIT_COUNT, "Bit index {idx} out of bounds");
        let (group_idx, item_idx) = Self::idxs(idx);
        self.0[group_idx] &= !(1 << item_idx);
    }

    /// Unsets all bits in the given range.
    ///
    /// # Panics
    /// Panics if `range.start >= BIT_COUNT` or `range.end > BIT_COUNT`.
    ///
    /// # Examples
    /// ```
    /// use light_bitmap::{BitMap, bucket_count};
    ///
    /// let mut bm = BitMap::<8, { bucket_count(8) }>::with_all_set();
    /// bm.unset_range(2..6);
    /// assert!(!bm.is_set(2));
    /// assert!(!bm.is_set(5));
    /// assert!(bm.is_set(6));
    /// ```
    pub fn unset_range(&mut self, range: Range<usize>) {
        assert!(
            range.start < BIT_COUNT,
            "Range start {} out of bounds",
            range.start
        );
        assert!(
            range.end <= BIT_COUNT,
            "Range end {} out of bounds",
            range.end
        );

        if range.start >= range.end {
            return;
        }

        let (start_byte, start_bit) = Self::idxs(range.start);
        let (end_byte, end_bit) = Self::idxs(range.end - 1);

        // all within one byte
        if start_byte == end_byte {
            let width = end_bit - start_bit + 1;
            let mask = !ones_mask(start_bit, width);
            self.0[start_byte] &= mask;
            return;
        }

        // unset bits in first byte
        let first_mask = (1u8 << start_bit) - 1;
        self.0[start_byte] &= first_mask;

        // unset full bytes in between
        for byte in &mut self.0[start_byte + 1..end_byte] {
            *byte = 0;
        }

        // unset bits in last byte
        let width = end_bit + 1;
        let last_mask = !ones_mask(0, width);
        self.0[end_byte] &= last_mask;
    }

    /// Toggles the bit at the given index.
    ///
    /// Returns the previous value of the bit (before the toggle).
    ///
    /// # Panics
    /// Panics if `idx >= BIT_COUNT`.
    ///
    /// # Examples
    /// ```
    /// use light_bitmap::{BitMap, bucket_count};
    ///
    /// let mut bm = BitMap::<8, { bucket_count(8) }>::new();
    /// assert_eq!(bm.toggle(4), false); // flipped from false to true
    /// assert_eq!(bm.toggle(4), true);  // flipped from true to false
    /// ```
    #[inline]
    pub fn toggle(&mut self, idx: usize) -> bool {
        assert!(idx < BIT_COUNT, "Bit index {idx} out of bounds");
        let (group_idx, item_idx) = Self::idxs(idx);
        let bit = self.0[group_idx] & 1 << item_idx != 0;
        self.0[group_idx] ^= 1 << item_idx;
        bit
    }

    /// Returns `true` if the bit at the given index is set.
    ///
    /// # Panics
    /// Panics if `idx >= BIT_COUNT`.
    ///
    /// # Examples
    /// ```
    /// use light_bitmap::{BitMap, bucket_count};
    ///
    /// let mut bm = BitMap::<8, { bucket_count(8) }>::new();
    /// bm.set(1);
    /// assert!(bm.is_set(1));
    /// assert!(!bm.is_set(0));
    /// ```
    #[inline]
    pub fn is_set(&self, idx: usize) -> bool {
        assert!(idx < BIT_COUNT, "Bit index {idx} out of bounds");
        let (group_idx, item_idx) = Self::idxs(idx);
        self.0[group_idx] & 1 << item_idx != 0
    }

    #[inline]
    fn idxs(idx: usize) -> (usize, usize) {
        (idx / 8, idx % 8)
    }

    /// Returns an iterator over all bits as `bool`, from least to most significant.
    ///
    /// The iterator yields exactly `BIT_COUNT` items in order.
    ///
    /// # Examples
    /// ```
    /// use light_bitmap::{BitMap, bucket_count};
    /// use core::array::from_fn;
    ///
    ///
    /// let bm = BitMap::<4, { bucket_count(4) }>::from_slice(&[true, false, true, false]);
    /// let mut bm_iter = bm.iter();
    /// assert_eq!(from_fn(|_| bm_iter.next().unwrap()), [true, false, true, false]);
    /// ```
    #[inline]
    pub fn iter(&self) -> BitMapIter<BIT_COUNT, BUCKET_COUNT> {
        BitMapIter {
            bytes: &self.0,
            group_idx: 0,
            item_idx: 0,
        }
    }

    /// Returns an iterator over the indices of all set bits, in ascending
    /// order.
    ///
    /// The iterator yields up to `BIT_COUNT` indices and is guaranteed to
    /// terminate. Iterating through the entire iterator runs in is O(max(k, b))
    /// where k is the number of set bits and b is the number of buckets.
    ///
    /// # Examples
    /// ```
    /// use light_bitmap::{BitMap, bucket_count};
    /// use core::array::from_fn;
    ///
    /// let bm = BitMap::<5, { bucket_count(5) }>::from_slice(&[true, false, true, false, true]);
    /// let mut ones_iter = bm.iter_ones();
    /// let ones = from_fn(|i| ones_iter.next().unwrap_or(999));
    /// assert_eq!(ones, [0, 2, 4, 999, 999]);
    /// ```
    #[inline]
    pub fn iter_ones(&self) -> IterOnes<BIT_COUNT, BUCKET_COUNT> {
        IterOnes {
            bytes: &self.0,
            byte_idx: 0,
            current: self.0[0],
            base_bit_idx: 0,
        }
    }

    /// Returns an iterator over the indices of all unset bits, in ascending
    /// order.
    ///
    /// The iterator yields up to `BIT_COUNT` indices and is guaranteed to
    /// terminate. Iterating through the entire iterator runs in is O(max(k, b))
    /// where k is the number of unset bits and b is the number of buckets.
    ///
    /// # Examples
    /// ```
    /// use light_bitmap::{BitMap, bucket_count};
    /// use core::array::from_fn;
    ///
    /// let bm = BitMap::<5, { bucket_count(5) }>::from_slice(&[true, false, true, false, true]);
    /// let mut zeros_iter = bm.iter_zeros();
    /// let zeros = from_fn(|i| zeros_iter.next().unwrap_or(999));
    /// assert_eq!(zeros, [1, 3, 999, 999, 999]);
    /// ```
    #[inline]
    pub fn iter_zeros(&self) -> IterZeros<BIT_COUNT, BUCKET_COUNT> {
        IterZeros {
            bytes: &self.0,
            byte_idx: 0,
            current: !self.0[0],
            base_bit_idx: 0,
        }
    }

    /// Returns a new bitmap representing the bitwise OR of `self` and `other`.
    ///
    /// Each bit in the result is set if it is set in either operand.
    ///
    /// # Examples
    /// ```
    /// use light_bitmap::{BitMap, bucket_count};
    ///
    /// let a = BitMap::<4, { bucket_count(4) }>::from_slice(&[true, false, true, false]);
    /// let b = BitMap::<4, { bucket_count(4) }>::from_slice(&[false, true, true, false]);
    /// let c = a.bit_or(&b);
    /// assert_eq!(c, BitMap::<4, { bucket_count(4) }>::from_slice(&[true, true, true, false]));
    /// ```
    #[inline]
    pub fn bit_or(&self, other: &Self) -> Self {
        Self(from_fn(|i| self.0[i] | other.0[i]))
    }

    /// Performs an in-place bitwise OR with another bitmap.
    ///
    /// Each bit in `self` is updated to the result of `self | other`.
    ///
    /// # Examples
    /// ```
    /// use light_bitmap::{BitMap, bucket_count};
    ///
    /// let mut a = BitMap::<4, { bucket_count(4) }>::from_slice(&[true, false, true, false]);
    /// let b = BitMap::<4, { bucket_count(4) }>::from_slice(&[false, true, true, false]);
    /// a.in_place_bit_or(&b);
    /// assert_eq!(a, BitMap::<4, { bucket_count(4) }>::from_slice(&[true, true, true, false]));
    /// ```
    #[inline]
    pub fn in_place_bit_or(&mut self, other: &Self) {
        for (self_byte, other_byte) in self.0.iter_mut().zip(other.0.iter()) {
            *self_byte |= other_byte
        }
    }

    /// Returns a new bitmap representing the bitwise AND of `self` and `other`.
    ///
    /// Each bit in the result is set only if it is set in both operands.
    ///
    /// # Examples
    /// ```
    /// use light_bitmap::{BitMap, bucket_count};
    ///
    /// let a = BitMap::<4, { bucket_count(4) }>::from_slice(&[true, false, true, false]);
    /// let b = BitMap::<4, { bucket_count(4) }>::from_slice(&[false, true, true, false]);
    /// let c = a.bit_and(&b);
    /// assert_eq!(c, BitMap::<4, { bucket_count(4) }>::from_slice(&[false, false, true, false]));
    /// ```
    #[inline]
    pub fn bit_and(&self, other: &Self) -> Self {
        Self(from_fn(|i| self.0[i] & other.0[i]))
    }

    /// Performs an in-place bitwise AND with another bitmap.
    ///
    /// Each bit in `self` is updated to the result of `self & other`.
    ///
    /// # Examples
    /// ```
    /// use light_bitmap::{BitMap, bucket_count};
    ///
    /// let mut a = BitMap::<4, { bucket_count(4) }>::from_slice(&[true, false, true, false]);
    /// let b = BitMap::<4, { bucket_count(4) }>::from_slice(&[false, true, true, false]);
    /// a.in_place_bit_and(&b);
    /// assert_eq!(a, BitMap::<4, { bucket_count(4) }>::from_slice(&[false, false, true, false]));
    /// ```
    #[inline]
    pub fn in_place_bit_and(&mut self, other: &Self) {
        for (self_byte, other_byte) in self.0.iter_mut().zip(other.0.iter()) {
            *self_byte &= other_byte
        }
    }

    /// Returns a new bitmap representing the bitwise XOR of `self` and `other`.
    ///
    /// Each bit in the result is set if it differs between the operands.
    ///
    /// # Examples
    /// ```
    /// use light_bitmap::{BitMap, bucket_count};
    ///
    /// let a = BitMap::<4, { bucket_count(4) }>::from_slice(&[true, false, true, false]);
    /// let b = BitMap::<4, { bucket_count(4) }>::from_slice(&[false, true, true, false]);
    /// let c = a.bit_xor(&b);
    /// assert_eq!(c, BitMap::<4, { bucket_count(4) }>::from_slice(&[true, true, false, false]));
    /// ```
    #[inline]
    pub fn bit_xor(&self, other: &Self) -> Self {
        Self(from_fn(|i| self.0[i] ^ other.0[i]))
    }

    /// Performs an in-place bitwise XOR with another bitmap.
    ///
    /// Each bit in `self` is updated to the result of `self ^ other`.
    ///
    /// # Examples
    /// ```
    /// use light_bitmap::{BitMap, bucket_count};
    ///
    /// let mut a = BitMap::<4, { bucket_count(4) }>::from_slice(&[true, false, true, false]);
    /// let b = BitMap::<4, { bucket_count(4) }>::from_slice(&[false, true, true, false]);
    /// a.in_place_bit_xor(&b);
    /// assert_eq!(a, BitMap::<4, { bucket_count(4) }>::from_slice(&[true, true, false, false]));
    /// ```
    #[inline]
    pub fn in_place_bit_xor(&mut self, other: &Self) {
        for (self_byte, other_byte) in self.0.iter_mut().zip(other.0.iter()) {
            *self_byte ^= other_byte
        }
    }

    /// Returns a new bitmap with each bit inverted (bitwise NOT).
    ///
    /// Each bit in the result is the inverse of the corresponding bit in self.
    ///
    /// # Examples
    /// ```
    /// use light_bitmap::{BitMap, bucket_count};
    ///
    /// let a = BitMap::<4, { bucket_count(4) }>::from_slice(&[false, false, true, false]);
    /// let b = a.bit_not();
    /// assert_eq!(b, BitMap::<4, { bucket_count(4) }>::from_slice(&[true, true, false, true]));
    /// ```
    #[inline]
    pub fn bit_not(&self) -> Self {
        let mut result = Self(from_fn(|i| !self.0[i]));
        result.clean_unused_bits();
        result
    }

    /// Inverts each bit of the bitmap in-place (bitwise NOT).
    ///
    /// Each bit in `self` is updated to the inverse of the corresponding bit in
    /// self.
    ///
    /// # Examples
    /// ```
    /// use light_bitmap::{BitMap, bucket_count};
    ///
    /// let mut a = BitMap::<4, { bucket_count(4) }>::from_slice(&[true, false, true, false]);
    /// a.in_place_bit_not();
    /// assert_eq!(a, BitMap::<4, { bucket_count(4) }>::from_slice(&[false, true, false, true]));
    /// ```
    #[inline]
    pub fn in_place_bit_not(&mut self) {
        for byte in &mut self.0 {
            *byte = !*byte;
        }
        self.clean_unused_bits();
    }

    /// Returns the number of set bits in the bitmap.
    ///
    /// # Examples
    /// ```
    /// use light_bitmap::{BitMap, bucket_count};
    ///
    /// let bm = BitMap::<4, { bucket_count(4) }>::from_slice(&[true, false, true, false]);
    /// assert_eq!(bm.popcount(), 2);
    /// ```
    #[inline]
    pub fn popcount(&self) -> usize {
        self.0.iter().map(|b| b.count_ones() as usize).sum()
    }

    /// Returns the index of the first set bit or `None` if all bits are unset.
    ///
    /// Bits are checked in ascending order from least to most significant.
    /// Returns `None` if all bits are unset. Runs in O(b) where b is the bucket
    /// count.
    ///
    /// # Examples
    /// ```
    /// use light_bitmap::{BitMap, bucket_count};
    ///
    /// let empty = BitMap::<4, { bucket_count(4) }>::new();
    /// assert_eq!(empty.first_set_bit(), None);
    ///
    /// let mut bm = BitMap::<4, { bucket_count(4) }>::new();
    /// bm.set(2);
    /// assert_eq!(bm.first_set_bit(), Some(2));
    /// ```
    pub fn first_set_bit(&self) -> Option<usize> {
        for (i, byte) in self.0.iter().enumerate() {
            if *byte != 0 {
                let bit = byte.trailing_zeros() as usize;
                return Some(i * 8 + bit);
            }
        }
        None
    }

    #[inline]
    const fn clean_unused_bits(&mut self) {
        let bits_in_last = BIT_COUNT % 8;
        if bits_in_last != 0 {
            let mask = (1 << bits_in_last) - 1;
            self.0[BUCKET_COUNT - 1] &= mask;
        }
    }

    /// Does a left shift by `n` positions, filling with unset bits. This means
    /// bits are shifted towards higher bit indices.
    ///
    /// Bits that are shifted beyond `BIT_COUNT` are lost.
    /// If `n >= BIT_COUNT`, the bitmap is cleared.
    ///
    /// # Examples
    /// ```
    /// use light_bitmap::{BitMap, bucket_count};
    ///
    /// let mut bm = BitMap::<4, { bucket_count(4) }>::from_slice(&[true, false, true, false]);
    /// bm.shift_left(1);
    /// assert_eq!(bm, BitMap::<4, { bucket_count(4) }>::from_slice(&[false, true, false, true]));
    /// ```
    pub fn shift_left(&mut self, n: usize) {
        if n >= BIT_COUNT {
            self.0.fill(0);
            return;
        }
        let (byte_shift, bit_shift) = Self::idxs(n);

        if byte_shift > 0 {
            for i in (byte_shift..BUCKET_COUNT).rev() {
                self.0[i] = self.0[i - byte_shift];
            }
            for i in 0..byte_shift {
                self.0[i] = 0;
            }
        }

        if bit_shift > 0 {
            for i in (0..BUCKET_COUNT).rev() {
                let high = *self.0.get(i.wrapping_sub(1)).unwrap_or(&0);
                self.0[i] <<= bit_shift;
                self.0[i] |= high >> (8 - bit_shift);
            }
        }

        self.clean_unused_bits();
    }

    /// Does a right shift by `n` positions, filling with unset bits. This means
    /// bits are shifted towards lower bit indices.
    ///
    /// Bits that are shifted beyond index 0 are lost.
    /// If `n >= BIT_COUNT`, the bitmap is cleared.
    ///
    /// # Examples
    /// ```
    /// use light_bitmap::{BitMap, bucket_count};
    ///
    /// let mut bm = BitMap::<4, { bucket_count(4) }>::from_slice(&[true, false, true, false]);
    /// bm.shift_right(1);
    /// assert_eq!(bm, BitMap::<4, { bucket_count(4) }>::from_slice(&[false, true, false, false]));
    /// ```
    pub fn shift_right(&mut self, n: usize) {
        if n >= BIT_COUNT {
            self.0.fill(0);
            return;
        }
        self.clean_unused_bits();

        let byte_shift = n / 8;
        let bit_shift = n % 8;

        if byte_shift > 0 {
            for i in 0..BUCKET_COUNT - byte_shift {
                self.0[i] = self.0[i + byte_shift];
            }
            for i in byte_shift..BUCKET_COUNT {
                self.0[i] = 0;
            }
        }

        if bit_shift > 0 {
            for i in 0..BUCKET_COUNT {
                let low = *self.0.get(i.wrapping_add(1)).unwrap_or(&0);
                self.0[i] >>= bit_shift;
                self.0[i] |= low << (8 - bit_shift);
            }
        }
    }

    /// Rotates all bits in direction of higher bit indices by `n` positions.
    /// Bits shifted out are reinserted on the other side.
    ///
    /// # Panics
    /// Panics if `BIT_COUNT == 0` or `BUCKET_COUNT != bucket_count(BIT_COUNT)`.
    ///
    /// # Examples
    /// ```
    /// use light_bitmap::{BitMap, bucket_count};
    ///
    /// let mut bm = BitMap::<4, { bucket_count(4) }>::from_slice(&[true, false, false, true]);
    /// bm.rotate_left(1);
    /// assert_eq!(bm, BitMap::<4, { bucket_count(4) }>::from_slice(&[true, true, false, false]));
    /// ```
    pub fn rotate_left(&mut self, n: usize) {
        // avoid division by zero
        runtime_assert_const_params(BIT_COUNT, BUCKET_COUNT);
        if n % BIT_COUNT == 0 {
            return;
        }
        let n = n % BIT_COUNT;
        let mut prev = self.is_set((BIT_COUNT - n) % BIT_COUNT);
        let mut bit_idx = 0;
        let mut start_idx = 0;
        for _ in 0..BIT_COUNT {
            let temp = self.is_set(bit_idx);
            if prev {
                self.set(bit_idx)
            } else {
                self.unset(bit_idx);
            }
            prev = temp;
            bit_idx = (bit_idx + n) % BIT_COUNT;
            if bit_idx == start_idx {
                start_idx += 1;
                bit_idx += 1;
                prev = self.is_set((bit_idx + BIT_COUNT - n) % BIT_COUNT)
            }
        }
    }

    /// Rotates all bits in direction of lower bit indices by `n` positions.
    /// Bits shifted out are reinserted on the other side.
    ///
    /// # Panics
    /// Panics if `BIT_COUNT == 0` or `BUCKET_COUNT != bucket_count(BIT_COUNT)`.
    ///
    /// # Examples
    /// ```
    /// use light_bitmap::{BitMap, bucket_count};
    ///
    /// let mut bm = BitMap::<4, { bucket_count(4) }>::from_slice(&[true, false, false, true]);
    /// bm.rotate_right(1);
    /// assert_eq!(bm, BitMap::<4, { bucket_count(4) }>::from_slice(&[false, false, true, true]));
    /// ```
    pub fn rotate_right(&mut self, n: usize) {
        self.rotate_left(BIT_COUNT - n % BIT_COUNT);
    }
}

impl<const BIT_COUNT: usize, const BUCKET_COUNT: usize> Default
    for BitMap<BIT_COUNT, BUCKET_COUNT>
{
    fn default() -> Self {
        Self::new()
    }
}

impl<'bitmap, const BIT_COUNT: usize, const BUCKET_COUNT: usize> IntoIterator
    for &'bitmap BitMap<BIT_COUNT, BUCKET_COUNT>
{
    type Item = bool;
    type IntoIter = BitMapIter<'bitmap, BIT_COUNT, BUCKET_COUNT>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<const BIT_COUNT: usize, const BUCKET_COUNT: usize> Debug for BitMap<BIT_COUNT, BUCKET_COUNT> {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        write!(f, "LSB -> ")?;
        for (i, bit) in self.iter().enumerate() {
            if i % 8 == 0 {
                write!(f, "{i}: ")?;
            }
            write!(f, "{}", if bit { '1' } else { '0' })?;
            if i % 8 == 7 && i < BUCKET_COUNT * 8 - 1 {
                write!(f, " ")?;
            }
        }
        write!(f, " <- MSB")?;
        Ok(())
    }
}

/// Constructs a bitmap from an iterator over `bool`s.
///
/// # Panics
/// Panics if the iterator yields more or fewer than `BIT_COUNT` elements, if
/// `BIT_COUNT == 0` or if `BUCKET_COUNT != bucket_count(BIT_COUNT)`.
impl<const BIT_COUNT: usize, const BUCKET_COUNT: usize> FromIterator<bool>
    for BitMap<BIT_COUNT, BUCKET_COUNT>
{
    fn from_iter<T: IntoIterator<Item = bool>>(iter: T) -> Self {
        runtime_assert_const_params(BIT_COUNT, BUCKET_COUNT);
        let mut bm = Self::new();
        let mut idx = 0;

        for bit in iter {
            if idx >= BIT_COUNT {
                panic!("Iterator yielded more than {BIT_COUNT} elements");
            }
            if bit {
                bm.set(idx);
            }
            idx += 1;
        }

        if idx != BIT_COUNT {
            panic!("Iterator yielded fewer than {BIT_COUNT} elements");
        }

        bm
    }
}

impl<const BIT_COUNT: usize, const BUCKET_COUNT: usize> BitAnd for BitMap<BIT_COUNT, BUCKET_COUNT> {
    type Output = Self;

    fn bitand(self, rhs: Self) -> Self::Output {
        self.bit_and(&rhs)
    }
}

impl<const BIT_COUNT: usize, const BUCKET_COUNT: usize> BitAndAssign
    for BitMap<BIT_COUNT, BUCKET_COUNT>
{
    fn bitand_assign(&mut self, rhs: Self) {
        self.in_place_bit_and(&rhs)
    }
}

impl<const BIT_COUNT: usize, const BUCKET_COUNT: usize> BitOr for BitMap<BIT_COUNT, BUCKET_COUNT> {
    type Output = Self;

    fn bitor(self, rhs: Self) -> Self::Output {
        self.bit_or(&rhs)
    }
}

impl<const BIT_COUNT: usize, const BUCKET_COUNT: usize> BitOrAssign
    for BitMap<BIT_COUNT, BUCKET_COUNT>
{
    fn bitor_assign(&mut self, rhs: Self) {
        self.in_place_bit_or(&rhs)
    }
}

impl<const BIT_COUNT: usize, const BUCKET_COUNT: usize> BitXor for BitMap<BIT_COUNT, BUCKET_COUNT> {
    type Output = Self;

    fn bitxor(self, rhs: Self) -> Self::Output {
        self.bit_xor(&rhs)
    }
}

impl<const BIT_COUNT: usize, const BUCKET_COUNT: usize> BitXorAssign
    for BitMap<BIT_COUNT, BUCKET_COUNT>
{
    fn bitxor_assign(&mut self, rhs: Self) {
        self.in_place_bit_xor(&rhs)
    }
}

impl<const BIT_COUNT: usize, const BUCKET_COUNT: usize> Not for BitMap<BIT_COUNT, BUCKET_COUNT> {
    type Output = Self;

    fn not(self) -> Self::Output {
        self.bit_not()
    }
}

impl<const BIT_COUNT: usize, const BUCKET_COUNT: usize> Shl<usize>
    for BitMap<BIT_COUNT, BUCKET_COUNT>
{
    type Output = Self;

    fn shl(mut self, rhs: usize) -> Self::Output {
        self.shift_left(rhs);
        self
    }
}

impl<const BIT_COUNT: usize, const BUCKET_COUNT: usize> ShlAssign<usize>
    for BitMap<BIT_COUNT, BUCKET_COUNT>
{
    fn shl_assign(&mut self, rhs: usize) {
        self.shift_left(rhs);
    }
}

impl<const BIT_COUNT: usize, const BUCKET_COUNT: usize> Shr<usize>
    for BitMap<BIT_COUNT, BUCKET_COUNT>
{
    type Output = Self;

    fn shr(mut self, rhs: usize) -> Self::Output {
        self.shift_right(rhs);
        self
    }
}

impl<const BIT_COUNT: usize, const BUCKET_COUNT: usize> ShrAssign<usize>
    for BitMap<BIT_COUNT, BUCKET_COUNT>
{
    fn shr_assign(&mut self, rhs: usize) {
        self.shift_right(rhs);
    }
}

/// Iterator over all bits in the bitmap as `bool` values.
///
/// Yields `true` for set bits and `false` for unset bits, starting from index 0.
///
/// Returned by [`BitMap::iter()`].
#[derive(Clone, Copy)]
pub struct BitMapIter<'bitmap, const BIT_COUNT: usize, const BUCKET_COUNT: usize> {
    bytes: &'bitmap [u8; BUCKET_COUNT],
    group_idx: usize,
    item_idx: usize,
}

impl<const BIT_COUNT: usize, const BUCKET_COUNT: usize> Iterator
    for BitMapIter<'_, BIT_COUNT, BUCKET_COUNT>
{
    type Item = bool;

    fn next(&mut self) -> Option<Self::Item> {
        let absolute_idx = self.group_idx * 8 + self.item_idx;
        if absolute_idx >= BIT_COUNT {
            return None;
        }
        let bit = self.bytes[self.group_idx] & 1 << self.item_idx;
        self.item_idx += 1;
        if self.item_idx == 8 {
            self.item_idx = 0;
            self.group_idx += 1;
        }
        Some(bit != 0)
    }
}

impl<const BIT_COUNT: usize, const BUCKET_COUNT: usize> FusedIterator
    for BitMapIter<'_, BIT_COUNT, BUCKET_COUNT>
{
}

/// Iterator over the indices of set bits in the bitmap.
///
/// Yields the positions of all bits that are set, in ascending order.
///
/// Returned by [`BitMap::iter_ones()`].
#[derive(Clone, Copy)]
pub struct IterOnes<'bitmap, const BIT_COUNT: usize, const BUCKET_COUNT: usize> {
    bytes: &'bitmap [u8; BUCKET_COUNT],
    byte_idx: usize,
    current: u8,
    base_bit_idx: usize,
}

impl<const BIT_COUNT: usize, const BUCKET_COUNT: usize> Iterator
    for IterOnes<'_, BIT_COUNT, BUCKET_COUNT>
{
    type Item = usize;

    fn next(&mut self) -> Option<Self::Item> {
        while self.byte_idx < BUCKET_COUNT {
            if self.current != 0 {
                let tz = self.current.trailing_zeros() as usize;
                let idx = self.base_bit_idx + tz;
                if idx >= BIT_COUNT {
                    return None;
                }
                self.current &= self.current - 1; // unset LSB
                return Some(idx);
            }

            self.byte_idx += 1;
            self.base_bit_idx += 8;
            self.current = *self.bytes.get(self.byte_idx).unwrap_or(&0);
        }
        None
    }
}

impl<const BIT_COUNT: usize, const BUCKET_COUNT: usize> FusedIterator
    for IterOnes<'_, BIT_COUNT, BUCKET_COUNT>
{
}

/// Iterator over the indices of unset bits in the bitmap.
///
/// Yields the positions of all bits that are unset, in ascending order.
///
/// Returned by [`BitMap::iter_zeros()`].
#[derive(Clone, Copy)]
pub struct IterZeros<'bitmap, const BIT_COUNT: usize, const BUCKET_COUNT: usize> {
    bytes: &'bitmap [u8; BUCKET_COUNT],
    byte_idx: usize,
    current: u8,
    base_bit_idx: usize,
}

impl<const BIT_COUNT: usize, const BUCKET_COUNT: usize> Iterator
    for IterZeros<'_, BIT_COUNT, BUCKET_COUNT>
{
    type Item = usize;

    fn next(&mut self) -> Option<Self::Item> {
        while self.byte_idx < BUCKET_COUNT {
            if self.current != 0 {
                let tz = self.current.trailing_zeros() as usize;
                let idx = self.base_bit_idx + tz;
                if idx >= BIT_COUNT {
                    self.current = 0; // avoid entering if block once exhausted
                    return None;
                }
                self.current &= self.current - 1; // unset LSB
                return Some(idx);
            }

            self.byte_idx += 1;
            self.base_bit_idx += 8;
            self.current = !*self.bytes.get(self.byte_idx).unwrap_or(&0);
        }
        None
    }
}

impl<const BIT_COUNT: usize, const BUCKET_COUNT: usize> FusedIterator
    for IterZeros<'_, BIT_COUNT, BUCKET_COUNT>
{
}