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
use core::num::NonZeroUsize;
use core::slice::SliceIndex;

#[cfg(feature = "alloc")]
use alloc::fmt::Debug;

use crate::BitBlock;
mod iter;

pub use iter::Bits;
pub use iter::Ones;
pub use iter::Zeros;

/// Represents a slice of bits. `B` is the internal representation of the [blocks](BitBlock) used for the [`BitSlice`]
#[cfg_attr(feature = "std", derive(Hash))]
#[repr(transparent)]
pub struct BitSlice<B: BitBlock>(pub [B]);

#[cfg(feature = "alloc")]
impl<B: BitBlock> Debug for BitSlice<B> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str("[")?;
        if f.alternate() {
            f.write_str("\n")?;
        } else {
            f.write_str(" ")?;
        }

        for (i, bit) in self.bits().enumerate() {
            if bit {
                f.write_str("1")?;
            } else {
                f.write_str("0")?;
            }

            if i == self.len_bits() - 1 {
                continue;
            }

            if i % B::BITS == (B::BITS - 1) {
                if f.alternate() {
                    f.write_str(",\n")?;
                } else {
                    f.write_str(", ")?;
                }
            } else if i % 8 == 7 {
                f.write_str(" ")?;
            }
        }

        if f.alternate() {
            f.write_str("\n")?;
        } else {
            f.write_str(" ")?;
        }
        f.write_str("]")
    }
}

impl<B: BitBlock> BitSlice<B> {
    /// Returns the length of `self` in blocks.
    #[inline(always)]
    pub fn len_blocks(&self) -> usize {
        self.0.len()
    }

    /// Returns the length of `self` in bits.
    #[inline(always)]
    pub fn len_bits(&self) -> usize {
        B::bit_index_from_block_index(self.len_blocks())
    }

    pub fn get_blocks<I: SliceIndex<[B]>>(&self, index: I) -> Option<&I::Output> {
        self.0.get(index)
    }

    pub fn get_blocks_mut<I: SliceIndex<[B]>>(&mut self, index: I) -> Option<&mut I::Output> {
        self.0.get_mut(index)
    }

    /// Iterates over the blocks in `Self`
    pub fn blocks(&self) -> core::slice::Iter<'_, B> {
        self.0.iter()
    }

    /// Mutable iterates over the blocks in `Self`
    pub fn blocks_mut(&mut self) -> core::slice::IterMut<'_, B> {
        self.0.iter_mut()
    }

    /// Iterates over the bits in `self`.
    pub fn bits(&self) -> Bits<'_, B> {
        Bits::from_slice(self)
    }

    /// Iterates over the indices of the `1`s in `self`.
    /// This is equivalent to `self.bits().enumerate().filter_map(|(i, bit)| bit.then_some(i))`, but
    /// it makes use of several optimizations and usually a count leading zero instruction or something similar.
    pub fn ones(&self) -> Ones<'_, B> {
        Ones::from_slice(self)
    }

    /// Iterates over the indices of the `0`s in `self`.
    /// This is equivalent to `self.bits().enumerate().filter_map(|(i, bit)| (!bit).then_some(i))`, but
    /// it makes use of several optimizations and usually a count leading zero instruction or something similar.
    pub fn zeros(&self) -> Zeros<'_, B> {
        Zeros::from_slice(self)
    }

    /// Returns true if the bit at `idx` is a `1`. If `idx` is out of range, `None` is returned.
    #[inline(always)]
    pub fn test(&self, idx: usize) -> Option<bool> {
        if B::get_block_index(idx) < self.len_blocks() {
            Some(unsafe { self.test_unchecked(idx) })
        } else {
            None
        }
    }

    /// Sets the bit at `idx` to `1`. If `idx` is out of range, `false` is returned.
    #[inline(always)]
    pub fn set_checked(&mut self, idx: usize) -> bool {
        if B::get_block_index(idx) < self.len_blocks() {
            unsafe { self.set_unchecked(idx) };
            true
        } else {
            false
        }
    }

    /// Sets the bit at `idx` to `0`. If `idx` is out of range, `false` is returned.
    #[inline(always)]
    pub fn reset_checked(&mut self, idx: usize) -> bool {
        if B::get_block_index(idx) < self.len_blocks() {
            unsafe { self.reset_unchecked(idx) };
            true
        } else {
            false
        }
    }

    /// Zeros all of the bits in `self`.
    pub fn clear(&mut self) {
        let blocks: &mut [B] = self.as_mut();

        for block in blocks {
            *block = B::ZERO;
        }
    }

    /// Does a `BitOrAssign` between `rhs` and `self`. If `rhs` is bigger than `self`, the overflowing bits are ignored.
    pub fn bit_or_assign_iter<I: IntoIterator<Item = B>>(&mut self, other: I) {
        for (block, other_block) in self.0.iter_mut().zip(other.into_iter()) {
            *block |= other_block;
        }
    }

    /// Does a `BitOrAssign` between `rhs` and `self`. If `rhs` is bigger than `self`, the overflowing bits are ignored. \
    /// This function is purely a convinience function for [`Self::bit_or_assign_iter`].
    ///
    /// Note: the reason why the `BitOrAssign` trait isn't used is because it requires that `Self` is `Sized`.
    #[inline(always)]
    pub fn bit_or_assign(&mut self, other: &Self) {
        self.bit_or_assign_raw(&other.0)
    }

    pub fn fill_ones_checked(&mut self, start: usize, length: NonZeroUsize) -> bool {
        let len_bits = self.len_bits();

        if start + length.get() <= len_bits && start < len_bits {
            unsafe {
                self.fill_ones_unchecked(start, length);
            }
            true
        } else {
            false
        }
    }

    pub fn fill_zeros_checked(&mut self, start: usize, length: NonZeroUsize) -> bool {
        let len_bits = self.len_bits();

        if start + length.get() <= len_bits && start < len_bits {
            unsafe {
                self.fill_zeros_unchecked(start, length);
            }
            true
        } else {
            false
        }
    }
}

impl<'a, B: BitBlock + 'a> BitSlice<B> {
    /// Does a `BitOrAssign` between `rhs` and `self`. If `rhs` is bigger than `self`, the overflowing bits are ignored. \
    /// This function is purely a convinience function for [`Self::bit_or_assign_iter`].
    /// # Example
    /// ```rust
    /// # use bitmap32::BitMap;
    /// let mut foo = BitMap::from([0b00110000u8, 0b00010010u8]);
    ///
    /// foo.bit_or_assign_raw(&[0b10000000]);
    /// assert_eq!(foo.test(0), Some(true));
    /// assert_eq!(foo.test(8), Some(false));
    /// ```    
    #[inline(always)]
    pub fn bit_or_assign_raw<I: IntoIterator<Item = &'a B>>(&mut self, other: I) {
        self.bit_or_assign_iter(other.into_iter().copied())
    }
}

impl<B: BitBlock> BitSlice<B> {
    /// Returns `true` if the bit at `idx` is `1`.
    /// # Safety
    /// This function is safe if and only if `idx < self.len_blocks()`.
    pub unsafe fn test_unchecked(&self, idx: usize) -> bool {
        debug_assert!(B::get_block_index(idx) < self.len_blocks());

        let block = self.0.get_unchecked(B::get_block_index(idx));

        block.wrapping_test_bit(idx)
    }

    /// Sets the bit at `idx` to `1`.
    /// # Safety
    /// This function is safe if and only if `idx < self.len_blocks()`.
    pub unsafe fn set_unchecked(&mut self, idx: usize) {
        debug_assert!(B::get_block_index(idx) < self.len_blocks());

        let block = self.0.get_unchecked_mut(B::get_block_index(idx));

        *block = block.wrapping_with_bit(idx);
    }

    /// Sets the bit at `idx` to `0`
    /// # Safety
    /// This function is safe if and only if `idx < self.len_blocks()`.
    pub unsafe fn reset_unchecked(&mut self, idx: usize) {
        debug_assert!(B::get_block_index(idx) < self.len_blocks());

        let block = self.0.get_unchecked_mut(B::get_block_index(idx));

        *block = block.wrapping_without_bit(idx);
    }

    /// Fills a region starting at bit index `start` with `1`s. TODO: test
    /// # Safety
    /// TODO
    pub unsafe fn fill_ones_unchecked(&mut self, start: usize, length: NonZeroUsize) {
        let blocks = &mut self.0;

        let block_index = B::get_block_index(start);
        let start = start % B::BITS;

        let mut remaining_len = length.get();
        let mut pos = start;
        let mut block_index = block_index;

        while let Some(non_zero_remaining_length) = NonZeroUsize::new(remaining_len) {
            let block: &mut B = blocks.get_unchecked_mut(block_index);
            block_index += 1;
            *block |= B::ones_mask(pos, non_zero_remaining_length);

            remaining_len = remaining_len.saturating_sub(B::BITS - pos);
            pos = 0;
        }
    }

    /// Fills a region starting at bit index `start` with `0`s. TODO: test
    /// # Safety
    /// TODO
    pub unsafe fn fill_zeros_unchecked(&mut self, start: usize, length: NonZeroUsize) {
        let blocks = &mut self.0;

        let block_index = B::get_block_index(start);
        let start = start % B::BITS;

        let mut remaining_len = length.get();
        let mut pos = start;
        let mut block_index = block_index;

        while let Some(non_zero_remaining_length) = NonZeroUsize::new(remaining_len) {
            let block: &mut B = blocks.get_unchecked_mut(block_index);
            block_index += 1;
            *block &= !B::ones_mask(pos, non_zero_remaining_length);

            remaining_len = remaining_len.saturating_sub(B::BITS - pos);
            pos = 0;
        }
    }
}
impl<B: BitBlock> AsRef<[B]> for BitSlice<B> {
    #[inline(always)]
    fn as_ref(&self) -> &[B] {
        &self.0
    }
}

impl<B: BitBlock> AsMut<[B]> for BitSlice<B> {
    #[inline(always)]
    fn as_mut(&mut self) -> &mut [B] {
        &mut self.0
    }
}

impl<B: BitBlock> AsRef<BitSlice<B>> for [B] {
    #[inline(always)]
    fn as_ref(&self) -> &BitSlice<B> {
        unsafe { &*(self as *const [B] as *const BitSlice<B>) }
    }
}

impl<B: BitBlock> AsMut<BitSlice<B>> for [B] {
    #[inline(always)]
    fn as_mut(&mut self) -> &mut BitSlice<B> {
        unsafe { &mut *(self as *mut [B] as *mut BitSlice<B>) }
    }
}