Skip to main content

arrow_buffer/util/
bit_chunk_iterator.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! Types for iterating over bitmasks in 64-bit chunks
19
20use crate::util::bit_util::ceil;
21use std::fmt::Debug;
22
23/// Iterates over an arbitrarily aligned byte buffer
24///
25/// Yields an iterator of aligned u64, along with the leading and trailing
26/// u64 necessary to align the buffer to a 8-byte boundary
27///
28/// This is unlike [`BitChunkIterator`] which only exposes a trailing u64,
29/// and consequently has to perform more work for each read
30#[derive(Debug)]
31pub struct UnalignedBitChunk<'a> {
32    lead_padding: usize,
33    trailing_padding: usize,
34
35    prefix: Option<u64>,
36    chunks: &'a [u64],
37    suffix: Option<u64>,
38}
39
40impl<'a> UnalignedBitChunk<'a> {
41    /// Create from a byte array, offset and length in bits
42    pub fn new(buffer: &'a [u8], offset: usize, len: usize) -> Self {
43        if len == 0 {
44            return Self {
45                lead_padding: 0,
46                trailing_padding: 0,
47                prefix: None,
48                chunks: &[],
49                suffix: None,
50            };
51        }
52
53        let byte_offset = offset / 8;
54        let offset_padding = offset % 8;
55
56        let bytes_len = (len + offset_padding).div_ceil(8);
57        let buffer = &buffer[byte_offset..byte_offset + bytes_len];
58
59        let prefix_mask = compute_prefix_mask(offset_padding);
60
61        // If less than 8 bytes, read into prefix
62        if buffer.len() <= 8 {
63            let (suffix_mask, trailing_padding) = compute_suffix_mask(len, offset_padding);
64            let prefix = read_u64(buffer) & suffix_mask & prefix_mask;
65
66            return Self {
67                lead_padding: offset_padding,
68                trailing_padding,
69                prefix: Some(prefix),
70                chunks: &[],
71                suffix: None,
72            };
73        }
74
75        // If less than 16 bytes, read into prefix and suffix
76        if buffer.len() <= 16 {
77            let (suffix_mask, trailing_padding) = compute_suffix_mask(len, offset_padding);
78            let prefix = read_u64(&buffer[..8]) & prefix_mask;
79            let suffix = read_u64(&buffer[8..]) & suffix_mask;
80
81            return Self {
82                lead_padding: offset_padding,
83                trailing_padding,
84                prefix: Some(prefix),
85                chunks: &[],
86                suffix: Some(suffix),
87            };
88        }
89
90        // Read into prefix and suffix as needed
91        // Safety: u64 has no invalid bit patterns so reinterpreting initialized u8 bytes as u64 is sound.
92        let (prefix, mut chunks, suffix) = unsafe { buffer.align_to::<u64>() };
93        assert!(
94            prefix.len() < 8 && suffix.len() < 8,
95            "align_to did not return largest possible aligned slice"
96        );
97
98        let (alignment_padding, prefix) = match (offset_padding, prefix.is_empty()) {
99            (0, true) => (0, None),
100            (_, true) => {
101                let prefix = chunks[0] & prefix_mask;
102                chunks = &chunks[1..];
103                (0, Some(prefix))
104            }
105            (_, false) => {
106                let alignment_padding = (8 - prefix.len()) * 8;
107
108                let prefix = (read_u64(prefix) & prefix_mask) << alignment_padding;
109                (alignment_padding, Some(prefix))
110            }
111        };
112
113        let lead_padding = offset_padding + alignment_padding;
114        let (suffix_mask, trailing_padding) = compute_suffix_mask(len, lead_padding);
115
116        let suffix = match (trailing_padding, suffix.is_empty()) {
117            (0, _) => None,
118            (_, true) => {
119                let suffix = chunks[chunks.len() - 1] & suffix_mask;
120                chunks = &chunks[..chunks.len() - 1];
121                Some(suffix)
122            }
123            (_, false) => Some(read_u64(suffix) & suffix_mask),
124        };
125
126        Self {
127            lead_padding,
128            trailing_padding,
129            prefix,
130            chunks,
131            suffix,
132        }
133    }
134
135    /// Returns the number of leading padding bits
136    pub fn lead_padding(&self) -> usize {
137        self.lead_padding
138    }
139
140    /// Returns the number of trailing padding bits
141    pub fn trailing_padding(&self) -> usize {
142        self.trailing_padding
143    }
144
145    /// Returns the prefix, if any
146    pub fn prefix(&self) -> Option<u64> {
147        self.prefix
148    }
149
150    /// Returns the suffix, if any
151    pub fn suffix(&self) -> Option<u64> {
152        self.suffix
153    }
154
155    /// Returns reference to the chunks
156    pub fn chunks(&self) -> &'a [u64] {
157        self.chunks
158    }
159
160    /// Returns an iterator over the chunks
161    #[inline]
162    pub fn iter(&self) -> UnalignedBitChunkIterator<'a> {
163        self.prefix
164            .into_iter()
165            .chain(self.chunks.iter().copied())
166            .chain(self.suffix)
167    }
168
169    /// Counts the number of ones
170    pub fn count_ones(&self) -> usize {
171        self.iter().map(|x| x.count_ones() as usize).sum()
172    }
173}
174
175impl<'a> IntoIterator for &UnalignedBitChunk<'a> {
176    type Item = u64;
177    type IntoIter = UnalignedBitChunkIterator<'a>;
178
179    fn into_iter(self) -> Self::IntoIter {
180        self.iter()
181    }
182}
183
184/// Iterator over an [`UnalignedBitChunk`]
185pub type UnalignedBitChunkIterator<'a> = std::iter::Chain<
186    std::iter::Chain<std::option::IntoIter<u64>, std::iter::Copied<std::slice::Iter<'a, u64>>>,
187    std::option::IntoIter<u64>,
188>;
189
190#[inline]
191fn read_u64(input: &[u8]) -> u64 {
192    let len = input.len().min(8);
193    let mut buf = [0_u8; 8];
194    buf[..len].copy_from_slice(input);
195    u64::from_le_bytes(buf)
196}
197
198#[inline]
199fn compute_prefix_mask(lead_padding: usize) -> u64 {
200    !((1 << lead_padding) - 1)
201}
202
203#[inline]
204fn compute_suffix_mask(len: usize, lead_padding: usize) -> (u64, usize) {
205    let trailing_bits = (len + lead_padding) % 64;
206
207    if trailing_bits == 0 {
208        return (u64::MAX, 0);
209    }
210
211    let trailing_padding = 64 - trailing_bits;
212    let suffix_mask = (1 << trailing_bits) - 1;
213    (suffix_mask, trailing_padding)
214}
215
216/// Iterates over an arbitrarily aligned byte buffer 64 bits at a time
217///
218/// [`Self::iter`] yields iterator of `u64`, and a remainder. The first byte in the buffer
219/// will be the least significant byte in output u64
220#[derive(Debug)]
221pub struct BitChunks<'a> {
222    buffer: &'a [u8],
223    /// offset inside a byte, guaranteed to be between 0 and 7 (inclusive)
224    bit_offset: usize,
225    /// number of complete u64 chunks
226    chunk_len: usize,
227    /// number of remaining bits, guaranteed to be between 0 and 63 (inclusive)
228    remainder_len: usize,
229}
230
231impl<'a> BitChunks<'a> {
232    /// Create a new [`BitChunks`] from a byte array, and an offset and length in bits
233    pub fn new(buffer: &'a [u8], offset: usize, len: usize) -> Self {
234        let end = offset.checked_add(len).expect("offset + len out of bounds");
235        assert!(ceil(end, 8) <= buffer.len(), "offset + len out of bounds");
236
237        let byte_offset = offset / 8;
238        let bit_offset = offset % 8;
239
240        // number of complete u64 chunks
241        let chunk_len = len / 64;
242        // number of remaining bits
243        let remainder_len = len % 64;
244
245        BitChunks::<'a> {
246            buffer: &buffer[byte_offset..],
247            bit_offset,
248            chunk_len,
249            remainder_len,
250        }
251    }
252}
253
254/// Iterator over chunks of 64 bits represented as an u64
255#[derive(Debug)]
256pub struct BitChunkIterator<'a> {
257    buffer: &'a [u8],
258    bit_offset: usize,
259    chunk_len: usize,
260    index: usize,
261}
262
263impl<'a> BitChunks<'a> {
264    /// Returns the number of remaining bits, guaranteed to be between 0 and 63 (inclusive)
265    #[inline]
266    pub const fn remainder_len(&self) -> usize {
267        self.remainder_len
268    }
269
270    /// Returns the number of `u64` chunks
271    #[inline]
272    pub const fn chunk_len(&self) -> usize {
273        self.chunk_len
274    }
275
276    /// Returns the bitmask of remaining bits
277    #[inline]
278    pub fn remainder_bits(&self) -> u64 {
279        let bit_len = self.remainder_len;
280        if bit_len == 0 {
281            0
282        } else {
283            let bit_offset = self.bit_offset;
284            // number of bytes to read
285            // might be one more than sizeof(u64) if the offset is in the middle of a byte
286            let byte_len = ceil(bit_len + bit_offset, 8);
287            // pointer to remainder bytes after all complete chunks
288            // Safety: the buffer contains `chunk_len * 8 + ceil(remainder_len + bit_offset, 8)`
289            // bytes, so offsetting by `chunk_len * 8` and reading `byte_len` bytes is in-bounds.
290            let base = unsafe {
291                self.buffer
292                    .as_ptr()
293                    .add(self.chunk_len * std::mem::size_of::<u64>())
294            };
295
296            let mut bits = unsafe { std::ptr::read(base) } as u64 >> bit_offset;
297            for i in 1..byte_len {
298                let byte = unsafe { std::ptr::read(base.add(i)) };
299                bits |= (byte as u64) << (i * 8 - bit_offset);
300            }
301
302            bits & ((1 << bit_len) - 1)
303        }
304    }
305
306    /// Return the number of `u64` that are needed to represent all bits
307    /// (including remainder).
308    ///
309    /// This is equal to `chunk_len + 1` if there is a remainder,
310    /// otherwise it is equal to `chunk_len`.
311    #[inline]
312    pub fn num_u64s(&self) -> usize {
313        if self.remainder_len == 0 {
314            self.chunk_len
315        } else {
316            self.chunk_len + 1
317        }
318    }
319
320    /// Return the number of *bytes* that are needed to represent all bits
321    /// (including remainder).
322    #[inline]
323    pub fn num_bytes(&self) -> usize {
324        ceil(self.chunk_len * 64 + self.remainder_len, 8)
325    }
326
327    /// Returns an iterator over chunks of 64 bits represented as an `u64`
328    #[inline]
329    pub const fn iter(&self) -> BitChunkIterator<'a> {
330        BitChunkIterator::<'a> {
331            buffer: self.buffer,
332            bit_offset: self.bit_offset,
333            chunk_len: self.chunk_len,
334            index: 0,
335        }
336    }
337
338    /// Returns an iterator over chunks of 64 bits, with the remaining bits zero padded to 64-bits
339    #[inline]
340    pub fn iter_padded(&self) -> impl Iterator<Item = u64> + 'a {
341        self.iter().chain(std::iter::once(self.remainder_bits()))
342    }
343}
344
345impl<'a> IntoIterator for BitChunks<'a> {
346    type Item = u64;
347    type IntoIter = BitChunkIterator<'a>;
348
349    fn into_iter(self) -> Self::IntoIter {
350        self.iter()
351    }
352}
353
354impl<'a> IntoIterator for &BitChunks<'a> {
355    type Item = u64;
356    type IntoIter = BitChunkIterator<'a>;
357
358    fn into_iter(self) -> Self::IntoIter {
359        self.iter()
360    }
361}
362
363impl Iterator for BitChunkIterator<'_> {
364    type Item = u64;
365
366    #[inline]
367    fn next(&mut self) -> Option<u64> {
368        let index = self.index;
369        if index >= self.chunk_len {
370            return None;
371        }
372
373        // cast to *const u64 should be fine since we are using read_unaligned below
374        #[expect(clippy::cast_ptr_alignment)]
375        let raw_data = self.buffer.as_ptr().cast::<u64>();
376
377        // bit-packed buffers are stored starting with the least-significant byte first
378        // so when reading as u64 on a big-endian machine, the bytes need to be swapped
379        // Safety: `index < self.chunk_len` and the buffer is at least `chunk_len * 8` bytes long,
380        // so `raw_data.add(index)` is a valid in-bounds pointer; `read_unaligned` handles
381        // any pointer alignment.
382        let current = unsafe { std::ptr::read_unaligned(raw_data.add(index)).to_le() };
383
384        let bit_offset = self.bit_offset;
385
386        let combined = if bit_offset == 0 {
387            current
388        } else {
389            // the constructor ensures that bit_offset is in 0..8
390            // that means we need to read at most one additional byte to fill in the high bits
391            // Safety: the buffer has at least one byte past the last chunk (the remainder byte
392            // needed for `bit_offset > 0`), so `index + 1` is within bounds.
393            let next =
394                unsafe { std::ptr::read_unaligned(raw_data.add(index + 1).cast::<u8>()) as u64 };
395
396            (current >> bit_offset) | (next << (64 - bit_offset))
397        };
398
399        self.index = index + 1;
400
401        Some(combined)
402    }
403
404    #[inline]
405    fn size_hint(&self) -> (usize, Option<usize>) {
406        (
407            self.chunk_len - self.index,
408            Some(self.chunk_len - self.index),
409        )
410    }
411}
412
413impl ExactSizeIterator for BitChunkIterator<'_> {
414    #[inline]
415    fn len(&self) -> usize {
416        self.chunk_len - self.index
417    }
418}
419
420#[cfg(test)]
421mod tests {
422    use rand::distr::uniform::UniformSampler;
423    use rand::distr::uniform::UniformUsize;
424    use rand::prelude::*;
425    use rand::rng;
426
427    use crate::buffer::Buffer;
428    use crate::util::bit_chunk_iterator::UnalignedBitChunk;
429
430    #[test]
431    fn test_iter_aligned() {
432        let input: &[u8] = &[0, 1, 2, 3, 4, 5, 6, 7];
433        let buffer: Buffer = Buffer::from(input);
434
435        let bitchunks = buffer.bit_chunks(0, 64);
436        let result = bitchunks.into_iter().collect::<Vec<_>>();
437
438        assert_eq!(vec![0x0706050403020100], result);
439    }
440
441    #[test]
442    fn test_iter_unaligned() {
443        let input: &[u8] = &[
444            0b00000000, 0b00000001, 0b00000010, 0b00000100, 0b00001000, 0b00010000, 0b00100000,
445            0b01000000, 0b11111111,
446        ];
447        let buffer: Buffer = Buffer::from(input);
448
449        let bitchunks = buffer.bit_chunks(4, 64);
450
451        assert_eq!(0, bitchunks.remainder_len());
452        assert_eq!(0, bitchunks.remainder_bits());
453
454        let result = bitchunks.into_iter().collect::<Vec<_>>();
455
456        assert_eq!(
457            vec![0b1111010000000010000000010000000010000000010000000010000000010000],
458            result
459        );
460    }
461
462    #[test]
463    fn test_iter_unaligned_remainder_1_byte() {
464        let input: &[u8] = &[
465            0b00000000, 0b00000001, 0b00000010, 0b00000100, 0b00001000, 0b00010000, 0b00100000,
466            0b01000000, 0b11111111,
467        ];
468        let buffer: Buffer = Buffer::from(input);
469
470        let bitchunks = buffer.bit_chunks(4, 66);
471
472        assert_eq!(2, bitchunks.remainder_len());
473        assert_eq!(0b00000011, bitchunks.remainder_bits());
474
475        let result = bitchunks.into_iter().collect::<Vec<_>>();
476
477        assert_eq!(
478            vec![0b1111010000000010000000010000000010000000010000000010000000010000],
479            result
480        );
481    }
482
483    #[test]
484    fn test_iter_unaligned_remainder_bits_across_bytes() {
485        let input: &[u8] = &[0b00111111, 0b11111100];
486        let buffer: Buffer = Buffer::from(input);
487
488        // remainder contains bits from both bytes
489        // result should be the highest 2 bits from first byte followed by lowest 5 bits of second bytes
490        let bitchunks = buffer.bit_chunks(6, 7);
491
492        assert_eq!(7, bitchunks.remainder_len());
493        assert_eq!(0b1110000, bitchunks.remainder_bits());
494    }
495
496    #[test]
497    fn test_iter_unaligned_remainder_bits_large() {
498        let input: &[u8] = &[
499            0b11111111, 0b00000000, 0b11111111, 0b00000000, 0b11111111, 0b00000000, 0b11111111,
500            0b00000000, 0b11111111,
501        ];
502        let buffer: Buffer = Buffer::from(input);
503
504        let bitchunks = buffer.bit_chunks(2, 63);
505
506        assert_eq!(63, bitchunks.remainder_len());
507        assert_eq!(
508            0b100_0000_0011_1111_1100_0000_0011_1111_1100_0000_0011_1111_1100_0000_0011_1111,
509            bitchunks.remainder_bits()
510        );
511    }
512
513    #[test]
514    fn test_iter_remainder_out_of_bounds() {
515        // allocating a full page should trigger a fault when reading out of bounds
516        const ALLOC_SIZE: usize = 4 * 1024;
517        let input = vec![0xFF_u8; ALLOC_SIZE];
518
519        let buffer: Buffer = Buffer::from_vec(input);
520
521        let bitchunks = buffer.bit_chunks(57, ALLOC_SIZE * 8 - 57);
522
523        assert_eq!(u64::MAX, bitchunks.iter().last().unwrap());
524        assert_eq!(0x7F, bitchunks.remainder_bits());
525    }
526
527    #[test]
528    #[should_panic(expected = "offset + len out of bounds")]
529    fn test_out_of_bound_should_panic_length_is_more_than_buffer_length() {
530        const ALLOC_SIZE: usize = 4 * 1024;
531        let input = vec![0xFF_u8; ALLOC_SIZE];
532
533        let buffer: Buffer = Buffer::from_vec(input);
534
535        // We are reading more than exists in the buffer
536        buffer.bit_chunks(0, (ALLOC_SIZE + 1) * 8);
537    }
538
539    #[test]
540    #[should_panic(expected = "offset + len out of bounds")]
541    fn test_out_of_bound_should_panic_length_is_more_than_buffer_length_but_not_when_not_using_ceil()
542     {
543        const ALLOC_SIZE: usize = 4 * 1024;
544        let input = vec![0xFF_u8; ALLOC_SIZE];
545
546        let buffer: Buffer = Buffer::from_vec(input);
547
548        // We are reading more than exists in the buffer
549        buffer.bit_chunks(0, (ALLOC_SIZE * 8) + 1);
550    }
551
552    #[test]
553    #[should_panic(expected = "offset + len out of bounds")]
554    fn test_out_of_bound_should_panic_when_offset_is_not_zero_and_length_is_the_entire_buffer_length()
555     {
556        const ALLOC_SIZE: usize = 4 * 1024;
557        let input = vec![0xFF_u8; ALLOC_SIZE];
558
559        let buffer: Buffer = Buffer::from_vec(input);
560
561        // We are reading more than exists in the buffer
562        buffer.bit_chunks(8, ALLOC_SIZE * 8);
563    }
564
565    #[test]
566    #[should_panic(expected = "offset + len out of bounds")]
567    fn test_out_of_bound_should_panic_when_offset_is_not_zero_and_length_is_the_entire_buffer_length_with_ceil()
568     {
569        const ALLOC_SIZE: usize = 4 * 1024;
570        let input = vec![0xFF_u8; ALLOC_SIZE];
571
572        let buffer: Buffer = Buffer::from_vec(input);
573
574        // We are reading more than exists in the buffer
575        buffer.bit_chunks(1, ALLOC_SIZE * 8);
576    }
577
578    #[test]
579    #[should_panic(expected = "offset + len out of bounds")]
580    fn test_out_of_bound_should_panic_when_offset_and_length_overflow() {
581        let buffer = Buffer::from(vec![0xFF_u8; 8]);
582        buffer.bit_chunks(1, usize::MAX);
583    }
584
585    #[test]
586    fn test_unaligned_bit_chunk_iterator() {
587        let buffer = Buffer::from(&[0xFF; 5]);
588        let unaligned = UnalignedBitChunk::new(buffer.as_slice(), 0, 40);
589
590        assert!(unaligned.chunks().is_empty()); // Less than 128 elements
591        assert_eq!(unaligned.lead_padding(), 0);
592        assert_eq!(unaligned.trailing_padding(), 24);
593        // 24x 1 bit then 40x 0 bits
594        assert_eq!(
595            unaligned.prefix(),
596            Some(0b0000000000000000000000001111111111111111111111111111111111111111)
597        );
598        assert_eq!(unaligned.suffix(), None);
599
600        let buffer = buffer.slice(1);
601        let unaligned = UnalignedBitChunk::new(buffer.as_slice(), 0, 32);
602
603        assert!(unaligned.chunks().is_empty()); // Less than 128 elements
604        assert_eq!(unaligned.lead_padding(), 0);
605        assert_eq!(unaligned.trailing_padding(), 32);
606        // 32x 1 bit then 32x 0 bits
607        assert_eq!(
608            unaligned.prefix(),
609            Some(0b0000000000000000000000000000000011111111111111111111111111111111)
610        );
611        assert_eq!(unaligned.suffix(), None);
612
613        let unaligned = UnalignedBitChunk::new(buffer.as_slice(), 5, 27);
614
615        assert!(unaligned.chunks().is_empty()); // Less than 128 elements
616        assert_eq!(unaligned.lead_padding(), 5); // 5 % 8 == 5
617        assert_eq!(unaligned.trailing_padding(), 32);
618        // 5x 0 bit, 27x 1 bit then 32x 0 bits
619        assert_eq!(
620            unaligned.prefix(),
621            Some(0b0000000000000000000000000000000011111111111111111111111111100000)
622        );
623        assert_eq!(unaligned.suffix(), None);
624
625        let unaligned = UnalignedBitChunk::new(buffer.as_slice(), 12, 20);
626
627        assert!(unaligned.chunks().is_empty()); // Less than 128 elements
628        assert_eq!(unaligned.lead_padding(), 4); // 12 % 8 == 4
629        assert_eq!(unaligned.trailing_padding(), 40);
630        // 4x 0 bit, 20x 1 bit then 40x 0 bits
631        assert_eq!(
632            unaligned.prefix(),
633            Some(0b0000000000000000000000000000000000000000111111111111111111110000)
634        );
635        assert_eq!(unaligned.suffix(), None);
636
637        let buffer = Buffer::from(&[0xFF; 14]);
638
639        // Verify buffer alignment
640        let (prefix, aligned, suffix) = unsafe { buffer.as_slice().align_to::<u64>() };
641        assert_eq!(prefix.len(), 0);
642        assert_eq!(aligned.len(), 1);
643        assert_eq!(suffix.len(), 6);
644
645        let unaligned = UnalignedBitChunk::new(buffer.as_slice(), 0, 112);
646
647        assert!(unaligned.chunks().is_empty()); // Less than 128 elements
648        assert_eq!(unaligned.lead_padding(), 0); // No offset and buffer aligned on 64-bit boundary
649        assert_eq!(unaligned.trailing_padding(), 16);
650        assert_eq!(unaligned.prefix(), Some(u64::MAX));
651        assert_eq!(unaligned.suffix(), Some((1 << 48) - 1));
652
653        let buffer = Buffer::from(&[0xFF; 16]);
654
655        // Verify buffer alignment
656        let (prefix, aligned, suffix) = unsafe { buffer.as_slice().align_to::<u64>() };
657        assert_eq!(prefix.len(), 0);
658        assert_eq!(aligned.len(), 2);
659        assert_eq!(suffix.len(), 0);
660
661        let unaligned = UnalignedBitChunk::new(buffer.as_slice(), 0, 128);
662
663        assert_eq!(unaligned.prefix(), Some(u64::MAX));
664        assert_eq!(unaligned.suffix(), Some(u64::MAX));
665        assert!(unaligned.chunks().is_empty()); // Exactly 128 elements
666
667        let buffer = Buffer::from(&[0xFF; 64]);
668
669        // Verify buffer alignment
670        let (prefix, aligned, suffix) = unsafe { buffer.as_slice().align_to::<u64>() };
671        assert_eq!(prefix.len(), 0);
672        assert_eq!(aligned.len(), 8);
673        assert_eq!(suffix.len(), 0);
674
675        let unaligned = UnalignedBitChunk::new(buffer.as_slice(), 0, 512);
676
677        // Buffer is completely aligned and larger than 128 elements -> all in chunks array
678        assert_eq!(unaligned.suffix(), None);
679        assert_eq!(unaligned.prefix(), None);
680        assert_eq!(unaligned.chunks(), [u64::MAX; 8].as_slice());
681        assert_eq!(unaligned.lead_padding(), 0);
682        assert_eq!(unaligned.trailing_padding(), 0);
683
684        let buffer = buffer.slice(1); // Offset buffer 1 byte off 64-bit alignment
685
686        // Verify buffer alignment
687        let (prefix, aligned, suffix) = unsafe { buffer.as_slice().align_to::<u64>() };
688        assert_eq!(prefix.len(), 7);
689        assert_eq!(aligned.len(), 7);
690        assert_eq!(suffix.len(), 0);
691
692        let unaligned = UnalignedBitChunk::new(buffer.as_slice(), 0, 504);
693
694        // Need a prefix with 1 byte of lead padding to bring the buffer into alignment
695        assert_eq!(unaligned.prefix(), Some(u64::MAX - 0xFF));
696        assert_eq!(unaligned.suffix(), None);
697        assert_eq!(unaligned.chunks(), [u64::MAX; 7].as_slice());
698        assert_eq!(unaligned.lead_padding(), 8);
699        assert_eq!(unaligned.trailing_padding(), 0);
700
701        let unaligned = UnalignedBitChunk::new(buffer.as_slice(), 17, 300);
702
703        // Out of 64-bit alignment by 8 bits from buffer, and 17 bits from provided offset
704        //   => need 8 + 17 = 25 bits of lead padding + 39 bits in prefix
705        //
706        // This leaves 300 - 17 = 261 bits remaining
707        //   => 4x 64-bit aligned 64-bit chunks + 5 remaining bits
708        //   => trailing padding of 59 bits
709        assert_eq!(unaligned.lead_padding(), 25);
710        assert_eq!(unaligned.trailing_padding(), 59);
711        assert_eq!(unaligned.prefix(), Some(u64::MAX - (1 << 25) + 1));
712        assert_eq!(unaligned.suffix(), Some(0b11111));
713        assert_eq!(unaligned.chunks(), [u64::MAX; 4].as_slice());
714
715        let unaligned = UnalignedBitChunk::new(buffer.as_slice(), 17, 0);
716
717        assert_eq!(unaligned.prefix(), None);
718        assert_eq!(unaligned.suffix(), None);
719        assert!(unaligned.chunks().is_empty());
720        assert_eq!(unaligned.lead_padding(), 0);
721        assert_eq!(unaligned.trailing_padding(), 0);
722
723        let unaligned = UnalignedBitChunk::new(buffer.as_slice(), 17, 1);
724
725        assert_eq!(unaligned.prefix(), Some(2));
726        assert_eq!(unaligned.suffix(), None);
727        assert!(unaligned.chunks().is_empty());
728        assert_eq!(unaligned.lead_padding(), 1);
729        assert_eq!(unaligned.trailing_padding(), 62);
730    }
731
732    #[test]
733    fn fuzz_unaligned_bit_chunk_iterator() {
734        let mut rng = rng();
735
736        let uusize = UniformUsize::new(usize::MIN, usize::MAX).unwrap();
737        for _ in 0..100 {
738            let mask_len = rng.random_range(0..1024);
739            let bools: Vec<_> = std::iter::from_fn(|| Some(rng.random()))
740                .take(mask_len)
741                .collect();
742
743            let buffer = Buffer::from_iter(bools.iter().copied());
744
745            let max_offset = 64.min(mask_len);
746            let offset = uusize.sample(&mut rng).checked_rem(max_offset).unwrap_or(0);
747
748            let max_truncate = 128.min(mask_len - offset);
749            let truncate = uusize
750                .sample(&mut rng)
751                .checked_rem(max_truncate)
752                .unwrap_or(0);
753
754            let unaligned =
755                UnalignedBitChunk::new(buffer.as_slice(), offset, mask_len - offset - truncate);
756
757            let bool_slice = &bools[offset..mask_len - truncate];
758
759            let count = unaligned.count_ones();
760            let expected_count = bool_slice.iter().filter(|x| **x).count();
761
762            assert_eq!(count, expected_count);
763
764            let collected: Vec<u64> = unaligned.iter().collect();
765
766            let get_bit = |idx: usize| -> bool {
767                let padded_index = idx + unaligned.lead_padding();
768                let byte_idx = padded_index / 64;
769                let bit_idx = padded_index % 64;
770                (collected[byte_idx] & (1 << bit_idx)) != 0
771            };
772
773            for (idx, b) in bool_slice.iter().enumerate() {
774                assert_eq!(*b, get_bit(idx))
775            }
776        }
777    }
778}