Skip to main content

imbl_sized_chunks/
bitmap.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5//! Fixed capacity inline bitmap, in-tree replacement for the archived
6//! `bitmaps` crate.
7//!
8//! `Bitmap<N>` stores `N` bits inline (no allocation) using the smallest
9//! storage type that fits: a machine word up to 128 bits, or an array of
10//! `u128`s up to 1024 bits. Only bit counts in the range `1..=1024` are
11//! supported; other sizes fail to compile.
12
13use core::fmt::Debug;
14
15/// Maps a bit count to a storage type carrying at least that many bits.
16#[doc(hidden)]
17pub trait Bits {
18    type Store: BitOps;
19}
20
21/// Type-level lookup from bit count to bitmap. There is an impl of [`Bits`]
22/// for every `BitsImpl<N>` with `N` in `1..=1024`.
23#[doc(hidden)]
24pub struct BitsImpl<const N: usize>;
25
26/// Bit operations on the storage backing a [`Bitmap`].
27#[doc(hidden)]
28pub trait BitOps: Copy + Default + Eq + Debug {
29    fn get(self, index: usize) -> bool;
30    /// Sets the bit, returning its previous value.
31    fn set(&mut self, index: usize, value: bool) -> bool;
32    fn count(self) -> usize;
33    fn is_empty(self) -> bool;
34    /// Index of the first set bit below `width`.
35    fn first_index(self, width: usize) -> Option<usize>;
36    /// Index of the first set bit strictly after `from`, below `width`.
37    fn next_index(self, from: usize, width: usize) -> Option<usize>;
38    /// Index of the last set bit below `width`.
39    fn last_index(self, width: usize) -> Option<usize>;
40    /// Index of the last set bit strictly before `before`.
41    fn prev_index(self, before: usize, width: usize) -> Option<usize>;
42    /// Index of the first clear bit below `width`.
43    fn first_false_index(self, width: usize) -> Option<usize>;
44    /// Index of the first clear bit strictly after `from`, below `width`.
45    fn next_false_index(self, from: usize, width: usize) -> Option<usize>;
46    /// Clear every bit at or above `width` and return the result.
47    fn mask(self, width: usize) -> Self;
48}
49
50#[inline]
51fn low_mask_u128(width: usize) -> u128 {
52    if width >= 128 {
53        u128::MAX
54    } else if width == 0 {
55        0
56    } else {
57        (1u128 << width) - 1
58    }
59}
60
61macro_rules! impl_int_ops {
62    ($t:ty) => {
63        impl BitOps for $t {
64            #[inline]
65            fn get(self, index: usize) -> bool {
66                (self >> index) & 1 == 1
67            }
68
69            #[inline]
70            fn set(&mut self, index: usize, value: bool) -> bool {
71                let prev = self.get(index);
72                if value {
73                    *self |= 1 << index;
74                } else {
75                    *self &= !(1 << index);
76                }
77                prev
78            }
79
80            #[inline]
81            fn count(self) -> usize {
82                <$t>::count_ones(self) as usize
83            }
84
85            #[inline]
86            fn is_empty(self) -> bool {
87                self == 0
88            }
89
90            #[inline]
91            fn first_index(self, width: usize) -> Option<usize> {
92                let x = self & (low_mask_u128(width) as $t);
93                if x == 0 {
94                    None
95                } else {
96                    Some(x.trailing_zeros() as usize)
97                }
98            }
99
100            #[inline]
101            fn next_index(self, from: usize, width: usize) -> Option<usize> {
102                let from = from + 1;
103                if from >= width {
104                    return None;
105                }
106                let x = self & (low_mask_u128(width) as $t) & (!0 << from);
107                if x == 0 {
108                    None
109                } else {
110                    Some(x.trailing_zeros() as usize)
111                }
112            }
113
114            #[inline]
115            fn last_index(self, width: usize) -> Option<usize> {
116                let x = self & (low_mask_u128(width) as $t);
117                if x == 0 {
118                    None
119                } else {
120                    Some(<$t>::BITS as usize - 1 - x.leading_zeros() as usize)
121                }
122            }
123
124            #[inline]
125            fn prev_index(self, before: usize, width: usize) -> Option<usize> {
126                self.last_index(width.min(before))
127            }
128
129            #[inline]
130            fn first_false_index(self, width: usize) -> Option<usize> {
131                let x = !self & (low_mask_u128(width) as $t);
132                if x == 0 {
133                    None
134                } else {
135                    Some(x.trailing_zeros() as usize)
136                }
137            }
138
139            #[inline]
140            fn next_false_index(self, from: usize, width: usize) -> Option<usize> {
141                let from = from + 1;
142                if from >= width {
143                    return None;
144                }
145                let x = !self & (low_mask_u128(width) as $t) & (!0 << from);
146                if x == 0 {
147                    None
148                } else {
149                    Some(x.trailing_zeros() as usize)
150                }
151            }
152
153            #[inline]
154            fn mask(self, width: usize) -> Self {
155                self & (low_mask_u128(width) as $t)
156            }
157        }
158    };
159}
160
161impl_int_ops!(u8);
162impl_int_ops!(u16);
163impl_int_ops!(u32);
164impl_int_ops!(u64);
165impl_int_ops!(u128);
166
167impl BitOps for bool {
168    #[inline]
169    fn get(self, index: usize) -> bool {
170        debug_assert!(index < 1);
171        self
172    }
173
174    #[inline]
175    fn set(&mut self, index: usize, value: bool) -> bool {
176        debug_assert!(index < 1);
177        core::mem::replace(self, value)
178    }
179
180    #[inline]
181    fn count(self) -> usize {
182        self as usize
183    }
184
185    #[inline]
186    fn is_empty(self) -> bool {
187        !self
188    }
189
190    #[inline]
191    fn first_index(self, _width: usize) -> Option<usize> {
192        if self {
193            Some(0)
194        } else {
195            None
196        }
197    }
198
199    #[inline]
200    fn next_index(self, _from: usize, _width: usize) -> Option<usize> {
201        None
202    }
203
204    #[inline]
205    fn last_index(self, width: usize) -> Option<usize> {
206        self.first_index(width)
207    }
208
209    #[inline]
210    fn prev_index(self, before: usize, _width: usize) -> Option<usize> {
211        // Only index 0 exists; it is strictly before any `before > 0`.
212        if before > 0 && self {
213            Some(0)
214        } else {
215            None
216        }
217    }
218
219    #[inline]
220    fn first_false_index(self, _width: usize) -> Option<usize> {
221        if self {
222            None
223        } else {
224            Some(0)
225        }
226    }
227
228    #[inline]
229    fn next_false_index(self, _from: usize, _width: usize) -> Option<usize> {
230        None
231    }
232
233    #[inline]
234    fn mask(self, _width: usize) -> Self {
235        self
236    }
237}
238
239macro_rules! impl_array_ops {
240    ($words:expr) => {
241        impl BitOps for [u128; $words] {
242            #[inline]
243            fn get(self, index: usize) -> bool {
244                (self[index >> 7] >> (index & 127)) & 1 == 1
245            }
246
247            #[inline]
248            fn set(&mut self, index: usize, value: bool) -> bool {
249                let prev = self.get(index);
250                let word = index >> 7;
251                let bit = index & 127;
252                if value {
253                    self[word] |= 1 << bit;
254                } else {
255                    self[word] &= !(1 << bit);
256                }
257                prev
258            }
259
260            #[inline]
261            fn count(self) -> usize {
262                let mut n = 0;
263                for word in self {
264                    n += word.count_ones() as usize;
265                }
266                n
267            }
268
269            #[inline]
270            fn is_empty(self) -> bool {
271                self.iter().all(|&word| word == 0)
272            }
273
274            #[inline]
275            fn first_index(self, width: usize) -> Option<usize> {
276                for wi in 0..$words {
277                    let base = wi * 128;
278                    let word = self[wi] & low_mask_u128(width.saturating_sub(base));
279                    if word != 0 {
280                        return Some(base + word.trailing_zeros() as usize);
281                    }
282                }
283                None
284            }
285
286            #[inline]
287            fn next_index(self, from: usize, width: usize) -> Option<usize> {
288                let from = from + 1;
289                if from >= width {
290                    return None;
291                }
292                let mut first = self[from >> 7] & (!0 << (from & 127));
293                first &= low_mask_u128(width - (from & !127));
294                if first != 0 {
295                    return Some((from & !127) + first.trailing_zeros() as usize);
296                }
297                for wi in (from >> 7) + 1..$words {
298                    let base = wi * 128;
299                    let word = self[wi] & low_mask_u128(width.saturating_sub(base));
300                    if word != 0 {
301                        return Some(base + word.trailing_zeros() as usize);
302                    }
303                }
304                None
305            }
306
307            #[inline]
308            fn last_index(self, width: usize) -> Option<usize> {
309                debug_assert!(width <= $words * 128);
310                if width == 0 {
311                    return None;
312                }
313                for wi in (0..=(width - 1) >> 7).rev() {
314                    let base = wi * 128;
315                    let word = self[wi] & low_mask_u128(width - base);
316                    if word != 0 {
317                        return Some(base + 127 - word.leading_zeros() as usize);
318                    }
319                }
320                None
321            }
322
323            #[inline]
324            fn prev_index(self, before: usize, width: usize) -> Option<usize> {
325                self.last_index(width.min(before))
326            }
327
328            #[inline]
329            fn first_false_index(self, width: usize) -> Option<usize> {
330                for wi in 0..$words {
331                    let base = wi * 128;
332                    let mask = low_mask_u128(width.saturating_sub(base));
333                    let word = !self[wi] & mask;
334                    if word != 0 {
335                        return Some(base + word.trailing_zeros() as usize);
336                    }
337                }
338                None
339            }
340
341            #[inline]
342            fn next_false_index(self, from: usize, width: usize) -> Option<usize> {
343                let from = from + 1;
344                if from >= width {
345                    return None;
346                }
347                let mut first = !self[from >> 7] & (!0 << (from & 127));
348                first &= low_mask_u128(width - (from & !127));
349                if first != 0 {
350                    return Some((from & !127) + first.trailing_zeros() as usize);
351                }
352                for wi in (from >> 7) + 1..$words {
353                    let base = wi * 128;
354                    let word = !self[wi] & low_mask_u128(width.saturating_sub(base));
355                    if word != 0 {
356                        return Some(base + word.trailing_zeros() as usize);
357                    }
358                }
359                None
360            }
361
362            #[inline]
363            fn mask(mut self, width: usize) -> Self {
364                for wi in 0..$words {
365                    let base = wi * 128;
366                    self[wi] &= low_mask_u128(width.saturating_sub(base));
367                }
368                self
369            }
370        }
371    };
372}
373
374impl_array_ops!(2);
375impl_array_ops!(3);
376impl_array_ops!(4);
377impl_array_ops!(5);
378impl_array_ops!(6);
379impl_array_ops!(7);
380impl_array_ops!(8);
381
382macro_rules! impl_bits {
383    ($store:ty, HEAD $($n:expr),*) => {
384        $(impl Bits for BitsImpl<$n> {
385            type Store = $store;
386        })*
387    };
388}
389
390// Bits impls for every width in 1..=1024, grouped by backing store.
391// Widths outside this range fail to compile, as they always have.
392impl_bits!(
393    bool, HEAD
394    1
395);
396impl_bits!(
397    u8, HEAD
398    2, 3, 4, 5, 6, 7, 8
399);
400impl_bits!(
401    u16, HEAD
402    9, 10, 11, 12, 13, 14, 15, 16
403);
404impl_bits!(
405    u32, HEAD
406    17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32
407);
408impl_bits!(
409    u64, HEAD
410    33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
411    56, 57, 58, 59, 60, 61, 62, 63, 64
412);
413impl_bits!(
414    u128, HEAD
415    65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87,
416    88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108,
417    109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126,
418    127, 128
419);
420impl_bits!(
421    [u128; 2], HEAD
422    129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146,
423    147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
424    165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182,
425    183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200,
426    201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218,
427    219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236,
428    237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
429    255, 256
430);
431impl_bits!(
432    [u128; 3], HEAD
433    257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274,
434    275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292,
435    293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310,
436    311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328,
437    329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346,
438    347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364,
439    365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382,
440    383, 384
441);
442impl_bits!(
443    [u128; 4], HEAD
444    385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402,
445    403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420,
446    421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438,
447    439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456,
448    457, 458, 459, 460, 461, 462, 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474,
449    475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492,
450    493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510,
451    511, 512
452);
453impl_bits!(
454    [u128; 5], HEAD
455    513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530,
456    531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548,
457    549, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 565, 566,
458    567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583, 584,
459    585, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 597, 598, 599, 600, 601, 602,
460    603, 604, 605, 606, 607, 608, 609, 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620,
461    621, 622, 623, 624, 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 635, 636, 637, 638,
462    639, 640
463);
464impl_bits!(
465    [u128; 6], HEAD
466    641, 642, 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657, 658,
467    659, 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676,
468    677, 678, 679, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689, 690, 691, 692, 693, 694,
469    695, 696, 697, 698, 699, 700, 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712,
470    713, 714, 715, 716, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 730,
471    731, 732, 733, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748,
472    749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766,
473    767, 768
474);
475impl_bits!(
476    [u128; 7], HEAD
477    769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786,
478    787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799, 800, 801, 802, 803, 804,
479    805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822,
480    823, 824, 825, 826, 827, 828, 829, 830, 831, 832, 833, 834, 835, 836, 837, 838, 839, 840,
481    841, 842, 843, 844, 845, 846, 847, 848, 849, 850, 851, 852, 853, 854, 855, 856, 857, 858,
482    859, 860, 861, 862, 863, 864, 865, 866, 867, 868, 869, 870, 871, 872, 873, 874, 875, 876,
483    877, 878, 879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894,
484    895, 896
485);
486impl_bits!(
487    [u128; 8], HEAD
488    897, 898, 899, 900, 901, 902, 903, 904, 905, 906, 907, 908, 909, 910, 911, 912, 913, 914,
489    915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 930, 931, 932,
490    933, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950,
491    951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 963, 964, 965, 966, 967, 968,
492    969, 970, 971, 972, 973, 974, 975, 976, 977, 978, 979, 980, 981, 982, 983, 984, 985, 986,
493    987, 988, 989, 990, 991, 992, 993, 994, 995, 996, 997, 998, 999, 1000, 1001, 1002, 1003,
494    1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018,
495    1019, 1020, 1021, 1022, 1023, 1024
496);
497
498/// A fixed capacity inline bitmap of `N` bits.
499///
500/// Used as the occupancy map inside [`SparseChunk`](crate::SparseChunk).
501/// Supports `N` in `1..=1024`; other sizes fail to compile.
502#[derive(Clone, Copy, PartialEq, Eq, Debug)]
503pub struct Bitmap<const N: usize>
504where
505    BitsImpl<N>: Bits,
506{
507    data: <BitsImpl<N> as Bits>::Store,
508}
509
510impl<const N: usize> Bitmap<N>
511where
512    BitsImpl<N>: Bits,
513{
514    /// Construct a bitmap with every bit clear.
515    #[inline]
516    pub fn new() -> Self {
517        Self {
518            data: Default::default(),
519        }
520    }
521
522    /// Construct a bitmap from a value of the same type as its backing store.
523    ///
524    /// Bits at or above index `N` are cleared, keeping the bitmap coherent:
525    /// `len()`, `is_empty()` and `is_full()` only ever count bits below `N`.
526    #[inline]
527    pub fn from_value(data: <BitsImpl<N> as Bits>::Store) -> Self {
528        Self {
529            data: data.mask(N),
530        }
531    }
532
533    /// Count the number of set bits.
534    #[inline]
535    pub fn len(self) -> usize {
536        self.data.count()
537    }
538
539    /// Test if the bitmap contains only clear bits.
540    #[inline]
541    pub fn is_empty(self) -> bool {
542        self.data.is_empty()
543    }
544
545    /// Test if all `N` bits are set.
546    #[inline]
547    pub fn is_full(self) -> bool {
548        self.data.count() == N
549    }
550
551    /// Get the value of the bit at a given index.
552    #[inline]
553    pub fn get(self, index: usize) -> bool {
554        debug_assert!(index < N);
555        self.data.get(index)
556    }
557
558    /// Set the value of the bit at a given index, returning the previous value.
559    ///
560    /// `index` must be `< N` (debug-asserted, as with the `bitmaps` crate);
561    /// writing a padding bit in a release build would create an incoherent
562    /// state, so `len()` would count a bit no scan or iterator can see.
563    #[inline]
564    pub fn set(&mut self, index: usize, value: bool) -> bool {
565        debug_assert!(index < N);
566        self.data.set(index, value)
567    }
568
569    /// Find the index of the first set bit.
570    #[inline]
571    pub fn first_index(self) -> Option<usize> {
572        self.data.first_index(N)
573    }
574
575    /// Find the index of the first set bit strictly after `index`.
576    #[inline]
577    pub fn next_index(self, index: usize) -> Option<usize> {
578        self.data.next_index(index, N)
579    }
580
581    /// Find the index of the last set bit.
582    #[inline]
583    pub fn last_index(self) -> Option<usize> {
584        self.data.last_index(N)
585    }
586
587    /// Find the index of the last set bit strictly before `index`.
588    #[inline]
589    pub fn prev_index(self, index: usize) -> Option<usize> {
590        self.data.prev_index(index, N)
591    }
592
593    /// Find the index of the first clear bit.
594    #[inline]
595    pub fn first_false_index(self) -> Option<usize> {
596        self.data.first_false_index(N)
597    }
598
599    /// Find the index of the first clear bit strictly after `index`.
600    #[inline]
601    pub fn next_false_index(self, index: usize) -> Option<usize> {
602        self.data.next_false_index(index, N)
603    }
604}
605
606impl<const N: usize> Default for Bitmap<N>
607where
608    BitsImpl<N>: Bits,
609{
610    #[inline]
611    fn default() -> Self {
612        Self::new()
613    }
614}
615
616/// An iterator over the indices of set bits in a [`Bitmap`].
617#[derive(Clone, Debug)]
618pub struct Iter<'a, const N: usize>
619where
620    BitsImpl<N>: Bits,
621{
622    head: Option<usize>,
623    tail: Option<usize>,
624    data: &'a Bitmap<N>,
625}
626
627impl<'a, const N: usize> Iterator for Iter<'a, N>
628where
629    BitsImpl<N>: Bits,
630{
631    type Item = usize;
632
633    fn next(&mut self) -> Option<Self::Item> {
634        let result;
635
636        match self.head {
637            None => {
638                result = self.data.first_index();
639            }
640            Some(index) => {
641                if index >= N {
642                    result = None;
643                } else {
644                    result = self.data.next_index(index);
645                }
646            }
647        }
648
649        if let Some(index) = result {
650            if let Some(tail) = self.tail {
651                if tail <= index {
652                    self.head = Some(N + 1);
653                    self.tail = None;
654                    return None;
655                }
656            } else {
657                // tail is already done
658                self.head = Some(N + 1);
659                return None;
660            }
661
662            self.head = Some(index);
663        } else {
664            self.head = Some(N + 1);
665        }
666
667        result
668    }
669
670    fn size_hint(&self) -> (usize, Option<usize>) {
671        // Sound upper bound only because the head/tail crossing checks yield
672        // each index at most once.
673        (0, Some(N))
674    }
675}
676
677impl<const N: usize> DoubleEndedIterator for Iter<'_, N>
678where
679    BitsImpl<N>: Bits,
680{
681    fn next_back(&mut self) -> Option<Self::Item> {
682        let result;
683
684        match self.tail {
685            None => {
686                result = None;
687            }
688            Some(index) => {
689                if index >= N {
690                    result = self.data.last_index();
691                } else {
692                    result = self.data.prev_index(index);
693                }
694            }
695        }
696
697        if let Some(index) = result {
698            if let Some(head) = self.head {
699                if head >= index {
700                    self.head = Some(N + 1);
701                    self.tail = None;
702                    return None;
703                }
704            }
705
706            self.tail = Some(index);
707        } else {
708            self.tail = None;
709        }
710
711        result
712    }
713}
714
715impl<const N: usize> core::iter::FusedIterator for Iter<'_, N> where BitsImpl<N>: Bits {}
716
717impl<'a, const N: usize> IntoIterator for &'a Bitmap<N>
718where
719    BitsImpl<N>: Bits,
720{
721    type Item = usize;
722    type IntoIter = Iter<'a, N>;
723
724    fn into_iter(self) -> Self::IntoIter {
725        Iter {
726            head: None,
727            tail: Some(N),
728            data: self,
729        }
730    }
731}
732
733#[cfg(test)]
734mod test {
735    use super::*;
736
737    fn exercise<const N: usize>()
738    where
739        BitsImpl<N>: Bits,
740    {
741        // Reference set of occupied indices, including both edges, word
742        // boundaries, and an even spread.
743        let mut indices = Vec::new();
744        for i in [0, 1, 7, 8, 9, 31, 32, 33, 63, 64, 65, 127, 128] {
745            if i < N {
746                indices.push(i);
747            }
748        }
749        let mut i = (N / 10).max(1);
750        while i < N {
751            if !indices.contains(&i) {
752                indices.push(i);
753            }
754            i += (N / 10).max(1);
755        }
756        if !indices.contains(&(N - 1)) {
757            indices.push(N - 1);
758        }
759        indices.sort_unstable();
760        // O(1) membership oracle; Vec::contains is too slow under Miri.
761        let mut occupied = vec![false; N];
762        for &i in &indices {
763            occupied[i] = true;
764        }
765
766        let mut b: Bitmap<N> = Bitmap::new();
767        assert!(b.is_empty());
768        assert!(!b.is_full());
769        assert_eq!(b.first_index(), None);
770        assert_eq!(b.last_index(), None);
771        assert_eq!(b.next_index(0), None);
772        assert_eq!(b.prev_index(0), None);
773        assert_eq!(b.first_false_index(), Some(0));
774        assert_eq!(b.into_iter().next(), None);
775        assert_eq!(b.into_iter().next_back(), None);
776
777        for &i in &indices {
778            assert!(!b.set(i, true));
779            assert!(b.set(i, true)); // previous value
780        }
781        assert_eq!(b.len(), indices.len());
782        assert_eq!(b.is_full(), indices.len() == N);
783        for &i in &indices {
784            assert!(b.get(i));
785        }
786
787        // Forward scan over set bits.
788        let mut from_oracle = indices.iter().copied();
789        assert_eq!(b.first_index(), from_oracle.next());
790        for (k, (&i, &j)) in indices.iter().zip(indices.iter().skip(1)).enumerate() {
791            assert_eq!(b.next_index(i), Some(j));
792            assert_eq!(b.next_index(j), indices.get(k + 2).copied());
793        }
794        assert_eq!(b.next_index(indices[indices.len() - 1]), None);
795
796        // Reverse scan.
797        assert_eq!(b.last_index(), indices.last().copied());
798        for (&i, &j) in indices.iter().skip(1).zip(indices.iter()) {
799            assert_eq!(b.prev_index(i), Some(j));
800        }
801
802        // Clear bits.
803        let mut first_free = 0;
804        while first_free < N && occupied[first_free] {
805            first_free += 1;
806        }
807        if first_free < N {
808            assert_eq!(b.first_false_index(), Some(first_free));
809        }
810        for start in 0..N {
811            let mut expected = start + 1;
812            while expected < N && occupied[expected] {
813                expected += 1;
814            }
815            assert_eq!(
816                b.next_false_index(start),
817                if expected < N { Some(expected) } else { None }
818            );
819        }
820
821        // Iterator and reverse iterator.
822        assert_eq!(b.into_iter().collect::<Vec<_>>(), indices);
823        assert_eq!(b.into_iter().rev().collect::<Vec<_>>(), {
824            let mut v = indices.clone();
825            v.reverse();
826            v
827        });
828
829        // Mixed-direction drain yields each set bit exactly once, then
830        // stays exhausted (fused).
831        let mut it = b.into_iter();
832        let mut mixed = Vec::new();
833        while let Some(i) = it.next() {
834            mixed.push(i);
835            if let Some(j) = it.next_back() {
836                mixed.push(j);
837            }
838        }
839        assert_eq!(mixed.len(), indices.len());
840        let mut sorted = mixed.clone();
841        sorted.sort_unstable();
842        assert_eq!(sorted, indices);
843        assert_eq!(it.next(), None);
844        assert_eq!(it.next_back(), None);
845        assert_eq!(it.next(), None);
846
847        // Same, leading with next_back.
848        let mut it = b.into_iter();
849        let mut mixed = Vec::new();
850        while let Some(j) = it.next_back() {
851            mixed.push(j);
852            if let Some(i) = it.next() {
853                mixed.push(i);
854            }
855        }
856        assert_eq!(mixed.len(), indices.len());
857        let mut sorted = mixed;
858        sorted.sort_unstable();
859        assert_eq!(sorted, indices);
860        assert_eq!(it.next_back(), None);
861        assert_eq!(it.next(), None);
862
863        // Clearing.
864        for &i in &indices {
865            assert!(b.set(i, false));
866        }
867        assert!(b.is_empty());
868        assert_eq!(b.len(), 0);
869
870        // from_value round-trip.
871        for &i in &indices {
872            b.set(i, true);
873        }
874        let store: <BitsImpl<N> as Bits>::Store = b.data;
875        assert_eq!(Bitmap::from_value(store), b);
876    }
877
878    #[test]
879    fn from_value_normalizes_out_of_range_bits() {
880        // Integer-backed, non-aligned width.
881        let b: Bitmap<7> = Bitmap::from_value(0xff);
882        assert_eq!(b.len(), 7);
883        assert!(b.is_full());
884        assert_eq!(b.into_iter().collect::<Vec<_>>(), (0..7).collect::<Vec<_>>());
885
886        // Array-backed: full boundary word plus one bit into the partial word.
887        let b: Bitmap<129> = Bitmap::from_value([u128::MAX, u128::MAX]);
888        assert_eq!(b.len(), 129);
889        assert!(b.is_full());
890
891        let b: Bitmap<129> = Bitmap::from_value([0, u128::MAX]);
892        assert_eq!(b.len(), 1);
893        assert_eq!(b.first_index(), Some(128));
894        assert_eq!(b.next_index(128), None);
895        // 128 is the only set bit and also the last valid index: nothing
896        // clear can follow index 127 within the bitmap.
897        assert_eq!(b.next_false_index(127), None);
898    }
899
900    #[test]
901    fn bitmap_widths() {
902        exercise::<1>();
903        exercise::<2>();
904        exercise::<7>();
905        exercise::<8>();
906        exercise::<9>();
907        exercise::<16>();
908        exercise::<31>();
909        exercise::<32>();
910        exercise::<33>();
911        exercise::<61>();
912        exercise::<64>();
913        exercise::<65>();
914        exercise::<90>();
915        exercise::<127>();
916        exercise::<128>();
917        exercise::<129>();
918        exercise::<130>();
919        exercise::<200>();
920        exercise::<256>();
921        exercise::<257>();
922        exercise::<384>();
923        exercise::<513>();
924        exercise::<641>();
925        exercise::<769>();
926        exercise::<897>();
927        exercise::<1023>();
928        exercise::<1024>();
929    }
930
931    struct XorShift(u64);
932
933    impl XorShift {
934        fn next(&mut self) -> u64 {
935            self.0 ^= self.0 << 13;
936            self.0 ^= self.0 >> 7;
937            self.0 ^= self.0 << 17;
938            self.0
939        }
940    }
941
942    fn exercise_random<const N: usize>(seed: u64)
943    where
944        BitsImpl<N>: Bits,
945    {
946        // Fixed-seed pseudo-random membership at varying densities, checked
947        // against a sorted-Vec oracle.
948        let mut rng = XorShift(seed);
949        for round in 0..16usize {
950            let density = (round + 1) * 48; // out of 768, i.e. up to ~83%
951            let indices: Vec<usize> = (0..N)
952                .filter(|_| rng.next() % 768 < density as u64)
953                .collect();
954            // O(1) membership oracle; Vec::contains is too slow under Miri.
955            let mut occupied = vec![false; N];
956            for &i in &indices {
957                occupied[i] = true;
958            }
959
960            let mut b: Bitmap<N> = Bitmap::new();
961            for &i in &indices {
962                b.set(i, true);
963            }
964            for (i, &is) in occupied.iter().enumerate() {
965                assert_eq!(b.get(i), is);
966            }
967            assert_eq!(b.len(), indices.len());
968            assert_eq!(b.first_index(), indices.first().copied());
969            assert_eq!(b.last_index(), indices.last().copied());
970            assert!(b.into_iter().eq(indices.iter().copied()));
971            assert!(b.into_iter().rev().eq(indices.iter().rev().copied()));
972            for (&i, &j) in indices.iter().zip(indices.iter().skip(1)) {
973                assert_eq!(b.next_index(i), Some(j));
974                assert_eq!(b.prev_index(j), Some(i));
975            }
976            for start in (0..N).step_by(64) {
977                let mut expected = start + 1;
978                while expected < N && occupied[expected] {
979                    expected += 1;
980                }
981                assert_eq!(
982                    b.next_false_index(start),
983                    if expected < N { Some(expected) } else { None }
984                );
985            }
986        }
987    }
988
989    #[test]
990    fn bitmap_random() {
991        for seed in [0x9e3779b97f4a7c15, 0x243f6a8885a308d3, 42] {
992            exercise_random::<1>(seed);
993            exercise_random::<7>(seed);
994            exercise_random::<8>(seed);
995            exercise_random::<61>(seed);
996            exercise_random::<64>(seed);
997            exercise_random::<65>(seed);
998            exercise_random::<128>(seed);
999            exercise_random::<129>(seed);
1000            exercise_random::<256>(seed);
1001            exercise_random::<1000>(seed);
1002            exercise_random::<1024>(seed);
1003        }
1004    }
1005}