• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

vigna / sux-rs / 22033742966

15 Feb 2026 10:02AM UTC coverage: 79.023% (+0.05%) from 78.971%
22033742966

push

github

vigna
Grammar fixes; Succ/Pred default methods now use get_unchecked

14 of 15 new or added lines in 3 files covered. (93.33%)

1 existing line in 1 file now uncovered.

5112 of 6469 relevant lines covered (79.02%)

114004066.11 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

75.47
/src/bits/bit_field_vec.rs
1
/*
2
 * SPDX-FileCopyrightText: 2023 Inria
3
 * SPDX-FileCopyrightText: 2023 Sebastiano Vigna
4
 *
5
 * SPDX-License-Identifier: Apache-2.0 OR LGPL-2.1-or-later
6
 */
7

8
//! Vectors of bit fields of fixed width (AKA “compact arrays“, “bit array“,
9
//! etc.)
10
//!
11
//! Elements are stored contiguously, with no padding bits (in particular,
12
//! unless the bit width is a power of two some elements will be stored across
13
//! word boundaries).
14
//!
15
//! There are two flavors: [`BitFieldVec`], a mutable bit-field vector, and
16
//! [`AtomicBitFieldVec`], a mutable, thread-safe bit-field vector.
17
//!
18
//! These flavors depend on a backend, and presently we provide, given an
19
//! unsigned integer type `W` or an unsigned atomic integer type `A`:
20
//!
21
//! - `BitFieldVec<Vec<T>>`: a mutable, growable and resizable bit-field vector;
22
//! - `BitFieldVec<AsRef<[W]>>`: an immutable bit-field vector, useful for
23
//!   [ε-serde](https://crates.io/crates/epserde) support;
24
//! - `BitFieldVec<AsRef<[W]> + AsMut<[W]>>`: a mutable (but not resizable) bit
25
//!   vector;
26
//! - `AtomicBitFieldVec<AsRef<[A]>>`: a partially thread-safe, mutable (but not
27
//!   resizable) bit-field vector.
28
//!
29
//! More generally, the underlying type must satisfy the trait [`Word`] for
30
//! [`BitFieldVec`] and additionally [`IntoAtomic`] for [`AtomicBitFieldVec`].
31
//! A blanket implementation exposes slices of elements of type `W` as bit-field
32
//! vectors of width `W::BITS`, analogously for atomic types `A`.
33
//!
34
//! The traits [`BitFieldSlice`] and [`BitFieldSliceMut`] provide a uniform
35
//! interface to access to the content of (a reference to) the bit-field vector.
36
//! There is also a [`AtomicBitFieldSlice`] trait for atomic bit-field vectors.
37
//! Since they are also implemented for slices of words, they make it easy to
38
//! write generic code that works both on bit-field vectors and on slices of
39
//! words when you need to consider the bit width of each element.
40
//!
41
//! Note that the [`try_chunks_mut`](SliceByValueMut::try_chunks_mut) method is
42
//! part of the [`SliceByValueMut`] trait, and thus returns an iterator over
43
//! elements implementing [`SliceByValueMut`]; the elements, however, implement
44
//! also [`BitFieldSliceMut`], and you can use this property by adding the bound
45
//! `for<'a> BitFieldSliceMut<W, ChunksMut<'a>: Iterator<Item:
46
//! BitFieldSliceMut<W>>>`.
47
//!
48
//! Nothing is assumed about the content of the backend outside the
49
//! bits of the vector. Moreover, the content of the backend outside of the
50
//! vector is never modified by the methods of this structure.
51
//!
52
//! For high-speed unchecked scanning, we implement [`IntoUncheckedIterator`]
53
//! and [`IntoUncheckedBackIterator`] on a reference to this type. They are
54
//! used, for example, to provide
55
//! [predecessor](crate::traits::indexed_dict::Pred) and
56
//! [successor](crate::traits::indexed_dict::Succ) primitives for
57
//! [`EliasFano`].
58
//!
59
//! # Low-level support
60
//!
61
//! The methods [`addr_of`](BitFieldVec::addr_of) and
62
//! [`get_unaligned`](BitFieldVec::get_unaligned) can be used to manually
63
//! prefetch parts of the data structure, or read values using unaligned read,
64
//! when the bit width makes it possible.
65
//!
66
//! # Examples
67
//!
68
//! ```
69
//! # use sux::prelude::*;
70
//! # use bit_field_slice::*;
71
//! # use value_traits::slices::*;
72
//! // Bit field vector of bit width 5 and length 10, all entries set to zero
73
//! let mut b = <BitFieldVec<usize>>::new(5, 10);
74
//! assert_eq!(b.len(), 10);
75
//! assert_eq!(b.bit_width(), 5);
76
//! b.set_value(0, 3);
77
//! assert_eq!(b.index_value(0), 3);
78
//!
79
//! // Empty bit field vector of bit width 20 with capacity 10
80
//! let mut b = <BitFieldVec<usize>>::with_capacity(20, 10);
81
//! assert_eq!(b.len(), 0);
82
//! assert_eq!(b.bit_width(), 20);
83
//! b.push(20);
84
//! assert_eq!(b.len(), 1);
85
//! assert_eq!(b.index_value(0), 20);
86
//! assert_eq!(b.pop(), Some(20));
87
//!
88
//! // Convenience macro
89
//! let b = bit_field_vec![10; 4, 500, 2, 0, 1];
90
//! assert_eq!(b.len(), 5);
91
//! assert_eq!(b.bit_width(), 10);
92
//! assert_eq!(b.index_value(0), 4);
93
//! assert_eq!(b.index_value(1), 500);
94
//! assert_eq!(b.index_value(2), 2);
95
//! assert_eq!(b.index_value(3), 0);
96
//! assert_eq!(b.index_value(4), 1);
97
//! ```
98
#[cfg(feature = "rayon")]
99
use crate::RAYON_MIN_LEN;
100
use crate::prelude::{bit_field_slice::*, *};
101
use crate::utils::{
102
    CannotCastToAtomicError, transmute_boxed_slice_from_atomic, transmute_boxed_slice_into_atomic,
103
    transmute_vec_from_atomic, transmute_vec_into_atomic,
104
};
105
use crate::{panic_if_out_of_bounds, panic_if_value};
106
use anyhow::{Result, bail};
107
use common_traits::{
108
    AsBytes, Atomic, AtomicInteger, AtomicUnsignedInt, CastableInto, IntoAtomic, invariant_eq,
109
};
110
use mem_dbg::*;
111
#[cfg(feature = "rayon")]
112
use rayon::prelude::*;
113
use std::iter::FusedIterator;
114
use std::sync::atomic::{Ordering, compiler_fence, fence};
115
use value_traits::slices::{SliceByValue, SliceByValueMut};
116

117
/// Convenient, [`vec!`]-like macro to initialize `usize`-based bit-field
118
/// vectors.
119
///
120
/// - `bit_field_vec![width]`: creates an empty bit-field vector of given bit
121
///   width.
122
///
123
/// - `bit_field_vec![width => value; length]`: creates a bit-field vector of
124
///   given bit width and length, with all entries set to `value`.
125
///
126
/// - `bit_field_vec![width; v₀, v₁, … ]`: creates a bit-field vector of
127
///   given bit width with entries set to `v₀`, `v₁`, ….
128
///
129
/// # Examples
130
///
131
/// ```
132
/// use sux::prelude::*;
133
/// use bit_field_slice::*;
134
/// use value_traits::slices::*;
135
/// // Empty bit field vector of bit width 5
136
/// let b = bit_field_vec![5];
137
/// assert_eq!(b.len(), 0);
138
/// assert_eq!(b.bit_width(), 5);
139
///
140
/// // 10 values of bit width 6, all set to 3
141
/// let b = bit_field_vec![6 => 3; 10];
142
/// assert_eq!(b.len(), 10);
143
/// assert_eq!(b.bit_width(), 6);
144
/// assert_eq!(b.iter().all(|x| x == 3), true);
145
///
146
/// // List of values of bit width 10
147
/// let b = bit_field_vec![10; 4, 500, 2, 0, 1];
148
/// assert_eq!(b.len(), 5);
149
/// assert_eq!(b.bit_width(), 10);
150
/// assert_eq!(b.index_value(0), 4);
151
/// assert_eq!(b.index_value(1), 500);
152
/// assert_eq!(b.index_value(2), 2);
153
/// assert_eq!(b.index_value(3), 0);
154
/// assert_eq!(b.index_value(4), 1);
155
/// ```
156
#[macro_export]
157
macro_rules! bit_field_vec {
158
    ($w:expr) => {
159
        $crate::bits::BitFieldVec::<usize, _>::new($w, 0)
160
    };
161
    ($w:expr; $n:expr; $v:expr) => {
162
        compile_error!(
163
            "the syntax bit_field_vec![width; length; value] has been removed: use bit_field_vec![width => value; length] instead"
164
        )
165
    };
166
    ($w:expr => $v:expr; $n:expr) => {
167
        {
168
            let mut bit_field_vec = $crate::bits::BitFieldVec::<usize, _>::with_capacity($w, $n);
169
            // Force type
170
            let v: usize = $v;
171
            bit_field_vec.resize($n, v);
172
            bit_field_vec
173
        }
174
    };
175
    ($w:expr; $($x:expr),+ $(,)?) => {
176
        {
177
            let mut b = $crate::bits::BitFieldVec::<usize, _>::with_capacity($w, [$($x),+].len());
178
            $(
179
                // Force type
180
                let x: usize = $x;
181
                b.push(x);
182
            )*
183
            b
184
        }
185
    };
186
}
187

188
/// A vector of bit fields of fixed width (AKA “compact array“, “bit array“,
189
/// etc.).
190
///
191
/// See the [module documentation](crate::bits) for more details.
192
#[derive(Debug, Clone, Copy, Hash, MemDbg, MemSize, value_traits::Subslices)]
193
#[value_traits_subslices(bound = "B: AsRef<[W]>")]
194
#[derive(value_traits::SubslicesMut)]
195
#[value_traits_subslices_mut(bound = "B: AsRef<[W]> + AsMut<[W]>")]
196
#[cfg_attr(feature = "epserde", derive(epserde::Epserde))]
197
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
198
pub struct BitFieldVec<W: Word = usize, B = Vec<W>> {
199
    /// The underlying storage.
200
    bits: B,
201
    /// The bit width of the values stored in the vector.
202
    bit_width: usize,
203
    /// A mask with its lowest `bit_width` bits set to one.
204
    mask: W,
205
    /// The length of the vector.
206
    len: usize,
207
}
208

209
/// Robust, heavily checked mask function for constructors and similar methods.
210
fn mask<W: Word>(bit_width: usize) -> W {
11,913✔
211
    if bit_width == 0 {
11,913✔
212
        W::ZERO
409✔
213
    } else {
214
        W::MAX >> W::BITS.checked_sub(bit_width).expect("bit_width > W::BITS")
34,512✔
215
    }
216
}
217

218
impl<W: Word, B> BitFieldVec<W, B> {
219
    /// # Safety
220
    /// `len` * `bit_width` must be between 0 (included) and the number of
221
    /// bits in `bits` (included).
222
    #[inline(always)]
223
    pub unsafe fn from_raw_parts(bits: B, bit_width: usize, len: usize) -> Self {
3,223✔
224
        Self {
225
            bits,
226
            bit_width,
227
            mask: mask(bit_width),
6,446✔
228
            len,
229
        }
230
    }
231

232
    #[inline(always)]
233
    pub fn into_raw_parts(self) -> (B, usize, usize) {
3,122✔
234
        (self.bits, self.bit_width, self.len)
6,244✔
235
    }
236

237
    /// Modifies the bit field in place.
238
    ///
239
    /// # Safety
240
    /// This is unsafe because it's the caller's responsibility to ensure
241
    /// that the length is compatible with the modified bits.
242
    #[inline(always)]
243
    pub unsafe fn map<W2: Word, B2>(self, f: impl FnOnce(B) -> B2) -> BitFieldVec<W2, B2> {
×
244
        BitFieldVec {
245
            bits: f(self.bits),
×
246
            bit_width: self.bit_width,
×
247
            mask: mask(self.bit_width),
×
248
            len: self.len,
×
249
        }
250
    }
251
}
252

253
impl<W: Word, B: AsRef<[W]>> BitFieldVec<W, B> {
254
    /// Gets the address of the item storing (the first part of)
255
    /// the element of given index.
256
    ///
257
    /// This method is mainly useful for manually prefetching
258
    /// parts of the data structure.
259
    pub fn addr_of(&self, index: usize) -> *const W {
4✔
260
        let start_bit = index * self.bit_width;
8✔
261
        let word_index = start_bit / W::BITS;
8✔
262
        (&self.bits.as_ref()[word_index]) as *const _
8✔
263
    }
264

265
    /// Like [`SliceByValue::index_value`], but using unaligned reads.
266
    ///
267
    /// This method can be used only for bit width smaller than or equal to
268
    /// `W::BITS - 8 + 2` or equal to `W::BITS - 8 + 4` or `W::BITS`. Moreover,
269
    /// an additional padding word must be present at the end of the vector.
270
    ///
271
    /// Note that to guarantee the absence of undefined behavior this method
272
    /// has to perform several tests. Consider using
273
    /// [`get_unaligned_unchecked`](Self::get_unaligned_unchecked) if you are
274
    /// sure that the constraints are respected.
275
    ///
276
    /// # Panics
277
    ///
278
    /// This method will panic if the constraints above are not respected.
279
    pub fn get_unaligned(&self, index: usize) -> W {
65✔
280
        assert!(
65✔
281
            self.bit_width <= W::BITS - 8 + 2
65✔
282
                || self.bit_width == W::BITS - 8 + 4
24✔
283
                || self.bit_width == W::BITS
14✔
284
        );
285
        panic_if_out_of_bounds!(index, self.len);
183✔
286
        assert!(
61✔
287
            (index * self.bit_width) / W::BYTES + W::BYTES <= self.bits.as_ref().len() * W::BYTES
122✔
288
        );
289
        unsafe { self.get_unaligned_unchecked(index) }
180✔
290
    }
291

292
    /// Like [`SliceByValue::get_value_unchecked`], but using unaligned reads.
293
    ///
294
    /// # Safety
295
    ///
296
    /// This method can be used only for bit width smaller than or equal to
297
    /// `W::BITS - 8 + 2` or equal to `W::BITS - 8 + 4` or `W::BITS`. Moreover,
298
    /// an additional padding word must be present at the end of the vector.
299
    ///
300
    /// # Panics
301
    ///
302
    /// This method will panic in debug mode if the safety constraints are not
303
    /// respected.
304
    pub unsafe fn get_unaligned_unchecked(&self, index: usize) -> W {
65✔
305
        debug_assert!(
65✔
306
            self.bit_width <= W::BITS - 8 + 2
65✔
307
                || self.bit_width == W::BITS - 8 + 4
24✔
308
                || self.bit_width == W::BITS
14✔
309
        );
310
        let base_ptr = self.bits.as_ref().as_ptr() as *const u8;
122✔
311
        let start_bit = index * self.bit_width;
122✔
312
        debug_assert!(start_bit / W::BYTES + W::BYTES <= self.bits.as_ref().len() * W::BYTES);
183✔
313
        let ptr = unsafe { base_ptr.add(start_bit / 8) } as *const W;
180✔
314
        let word = unsafe { core::ptr::read_unaligned(ptr) };
180✔
315
        (word >> (start_bit % 8)) & self.mask
60✔
316
    }
317

318
    /// Returns the backend of the vector as a slice of `W`.
319
    pub fn as_slice(&self) -> &[W] {
3✔
320
        self.bits.as_ref()
3✔
321
    }
322
}
323
/// An iterator over non-overlapping chunks of a bit-field vector, starting at
324
/// the beginning of the vector.
325
///
326
/// When the vector len is not evenly divided by the chunk size, the last chunk
327
/// of the iteration will be shorter.
328
///
329
/// This struct is created by the
330
/// [`try_chunks_mut`](crate::bits::bit_field_vec::BitFieldVec#impl-BitFieldSliceMut<W>-for-BitFieldVec<W,+B>)
331
/// method.
332
pub struct ChunksMut<'a, W: Word> {
333
    remaining: usize,
334
    bit_width: usize,
335
    chunk_size: usize,
336
    iter: std::slice::ChunksMut<'a, W>,
337
}
338

339
impl<'a, W: Word> Iterator for ChunksMut<'a, W> {
340
    type Item = BitFieldVec<W, &'a mut [W]>;
341

342
    #[inline]
343
    fn next(&mut self) -> Option<Self::Item> {
104✔
344
        self.iter.next().map(|chunk| {
415✔
345
            let size = Ord::min(self.chunk_size, self.remaining);
412✔
346
            let next = unsafe { BitFieldVec::from_raw_parts(chunk, self.bit_width, size) };
515✔
347
            self.remaining -= size;
103✔
348
            next
103✔
349
        })
350
    }
351
}
352

353
impl<'a, W: Word> ExactSizeIterator for ChunksMut<'a, W> where
354
    std::slice::ChunksMut<'a, W>: ExactSizeIterator
355
{
356
}
357

358
impl<'a, W: Word> FusedIterator for ChunksMut<'a, W> where
359
    std::slice::ChunksMut<'a, W>: FusedIterator
360
{
361
}
362

363
impl<W: Word, B: AsRef<[W]>> BitFieldVec<W, B> {}
364

365
impl<W: Word> BitFieldVec<W, Vec<W>> {
366
    /// Creates a new zero-initialized vector of given bit width and length.
367
    pub fn new(bit_width: usize, len: usize) -> Self {
2,021✔
368
        // We need at least one word to handle the case of bit width zero.
369
        let n_of_words = Ord::max(1, (len * bit_width).div_ceil(W::BITS));
8,084✔
370
        Self {
371
            bits: vec![W::ZERO; n_of_words],
6,063✔
372
            bit_width,
373
            mask: mask(bit_width),
4,042✔
374
            len,
375
        }
376
    }
377

378
    /// Creates a new zero-initialized vector of given bit width and length,
379
    /// adding padding bits to the end of the vector so that unaligned reads are
380
    /// possible.
381
    ///
382
    /// Note that this convenience method is a one-off: if the vector is resized
383
    /// or expanded, the padding will be lost.
384
    pub fn new_unaligned(bit_width: usize, len: usize) -> Self {
103✔
385
        let n_of_words = (len * bit_width).div_ceil(W::BITS);
309✔
386
        Self {
387
            // We add a word at the end
388
            bits: vec![W::ZERO; n_of_words + 1],
309✔
389
            bit_width,
390
            mask: mask(bit_width),
206✔
391
            len,
392
        }
393
    }
394

395
    /// Creates an empty vector that doesn't need to reallocate for up to
396
    /// `capacity` elements.
397
    pub fn with_capacity(bit_width: usize, capacity: usize) -> Self {
1,167✔
398
        // We need at least one word to handle the case of bit width zero.
399
        let n_of_words = Ord::max(1, (capacity * bit_width).div_ceil(W::BITS));
4,668✔
400
        Self {
401
            bits: Vec::with_capacity(n_of_words),
3,501✔
402
            bit_width,
403
            mask: mask(bit_width),
1,167✔
404
            len: 0,
405
        }
406
    }
407

408
    /// Sets the length.
409
    ///
410
    /// # Safety
411
    ///
412
    /// `len * bit_width` must be at most `self.bits.len() * W::BITS`. Note that
413
    /// setting the length might result in reading uninitialized data.
414
    pub unsafe fn set_len(&mut self, len: usize) {
1✔
415
        debug_assert!(len * self.bit_width <= self.bits.len() * W::BITS);
3✔
416
        self.len = len;
1✔
417
    }
418

419
    /// Sets len to 0.
420
    pub fn clear(&mut self) {
1✔
421
        self.len = 0;
1✔
422
    }
423

424
    /// Returns the bit width of the values inside the vector.
425
    pub fn bit_width(&self) -> usize {
315✔
426
        debug_assert!(self.bit_width <= W::BITS);
630✔
427
        self.bit_width
315✔
428
    }
429

430
    /// Returns the mask used to extract values from the vector.
431
    /// This will keep the lowest `bit_width` bits.
432
    pub fn mask(&self) -> W {
312✔
433
        self.mask
312✔
434
    }
435

436
    /// Creates a new vector by copying a slice; the bit width will be the minimum
437
    /// width sufficient to hold all values in the slice.
438
    ///
439
    /// Returns an error if the bit width of the values in `slice` is larger than
440
    /// `W::BITS`.
441
    pub fn from_slice<SW>(slice: &impl BitFieldSlice<SW>) -> Result<Self>
3✔
442
    where
443
        SW: Word + CastableInto<W>,
444
    {
445
        let mut max_len: usize = 0;
9✔
446
        for i in 0..slice.len() {
6,003✔
447
            max_len = Ord::max(max_len, unsafe {
9,000✔
448
                slice.get_value_unchecked(i).len() as usize
9,000✔
449
            });
450
        }
451

452
        if max_len > W::BITS {
3✔
453
            bail!(
1✔
454
                "Cannot convert a slice of bit width {} into a slice with W = {}",
×
455
                max_len,
×
456
                std::any::type_name::<W>()
1✔
457
            );
458
        }
459
        let mut result = Self::new(max_len, slice.len());
10✔
460
        for i in 0..slice.len() {
4,002✔
461
            unsafe { result.set_value_unchecked(i, slice.get_value_unchecked(i).cast()) };
12,000✔
462
        }
463

464
        Ok(result)
2✔
465
    }
466

467
    /// Adds a value at the end of the vector.
468
    pub fn push(&mut self, value: W) {
2,419✔
469
        panic_if_value!(value, self.mask, self.bit_width);
7,257✔
470
        if (self.len + 1) * self.bit_width > self.bits.len() * W::BITS {
5,240✔
471
            self.bits.push(W::ZERO);
402✔
472
        }
473
        unsafe {
474
            self.set_value_unchecked(self.len, value);
7,257✔
475
        }
476
        self.len += 1;
2,419✔
477
    }
478

479
    /// Truncates or extends with `value` the vector.
480
    pub fn resize(&mut self, new_len: usize, value: W) {
1,162✔
481
        panic_if_value!(value, self.mask, self.bit_width);
3,486✔
482
        if new_len > self.len {
1,162✔
483
            if new_len * self.bit_width > self.bits.len() * W::BITS {
3,483✔
484
                self.bits
2,322✔
485
                    .resize((new_len * self.bit_width).div_ceil(W::BITS), W::ZERO);
2,322✔
486
            }
487
            for i in self.len..new_len {
807,721✔
488
                unsafe {
489
                    self.set_value_unchecked(i, value);
2,419,680✔
490
                }
491
            }
492
        }
493
        self.len = new_len;
1,162✔
494
    }
495

496
    /// Removes and returns a value from the end of the vector.
497
    ///
498
    /// Returns None if the [`BitFieldVec`] is empty.
499
    pub fn pop(&mut self) -> Option<W> {
1,002✔
500
        if self.len == 0 {
1,002✔
501
            return None;
2✔
502
        }
503
        let value = self.index_value(self.len - 1);
4,000✔
504
        self.len -= 1;
1,000✔
505
        Some(value)
1,000✔
506
    }
507
}
508

509
impl<W: Word, B: AsRef<[W]> + AsMut<[W]>> BitFieldVec<W, B> {}
510

511
impl<W: Word, T> BitWidth<W> for BitFieldVec<W, T> {
512
    #[inline(always)]
513
    fn bit_width(&self) -> usize {
11,412✔
514
        debug_assert!(self.bit_width <= W::BITS);
22,824✔
515
        self.bit_width
11,412✔
516
    }
517
}
518

519
impl<W: Word, B: AsRef<[W]>> SliceByValue for BitFieldVec<W, B> {
520
    type Value = W;
521
    #[inline(always)]
522
    fn len(&self) -> usize {
174,944✔
523
        self.len
174,944✔
524
    }
525

526
    unsafe fn get_value_unchecked(&self, index: usize) -> W {
52,655,444✔
527
        let pos = index * self.bit_width;
105,310,888✔
528
        let word_index = pos / W::BITS;
105,310,888✔
529
        let bit_index = pos % W::BITS;
105,310,888✔
530
        let bits = self.bits.as_ref();
157,966,332✔
531

532
        unsafe {
533
            if bit_index + self.bit_width <= W::BITS {
52,655,444✔
534
                (*bits.get_unchecked(word_index) >> bit_index) & self.mask
78,871,382✔
535
            } else {
536
                ((*bits.get_unchecked(word_index) >> bit_index)
39,659,259✔
537
                    | (*bits.get_unchecked(word_index + 1) << (W::BITS - bit_index)))
26,439,506✔
538
                    & self.mask
13,219,753✔
539
            }
540
        }
541
    }
542
}
543

544
impl<W: Word, B: AsRef<[W]>> BitFieldSlice<W> for BitFieldVec<W, B> {
545
    fn as_slice(&self) -> &[W] {
×
546
        self.bits.as_ref()
×
547
    }
548
}
549

550
impl<W: Word, B: AsRef<[W]> + AsMut<[W]>> BitFieldSliceMut<W> for BitFieldVec<W, B> {
551
    #[inline(always)]
552
    fn mask(&self) -> W {
×
553
        self.mask
×
554
    }
555
    fn reset(&mut self) {
1✔
556
        let bit_len = self.len * self.bit_width;
2✔
557
        let full_words = bit_len / W::BITS;
2✔
558
        let residual = bit_len % W::BITS;
2✔
559
        let bits = self.bits.as_mut();
3✔
560
        bits[..full_words].iter_mut().for_each(|x| *x = W::ZERO);
3✔
561
        if residual != 0 {
2✔
562
            bits[full_words] &= W::MAX << residual;
1✔
563
        }
564
    }
565

566
    #[cfg(feature = "rayon")]
567
    fn par_reset(&mut self) {
1✔
568
        let bit_len = self.len * self.bit_width;
2✔
569
        let full_words = bit_len / W::BITS;
2✔
570
        let residual = bit_len % W::BITS;
2✔
571
        let bits = self.bits.as_mut();
3✔
572
        bits[..full_words]
1✔
573
            .par_iter_mut()
574
            .with_min_len(RAYON_MIN_LEN)
1✔
575
            .for_each(|x| *x = W::ZERO);
1✔
576
        if residual != 0 {
2✔
577
            bits[full_words] &= W::MAX << residual;
1✔
578
        }
579
    }
580

581
    fn as_mut_slice(&mut self) -> &mut [W] {
1✔
582
        self.bits.as_mut()
1✔
583
    }
584
}
585

586
/// Error type returned when [`try_chunks_mut`](SliceByValueMut::try_chunks_mut)
587
/// does not find sufficient alignment.
588
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
589
pub struct ChunksMutError<W: Word> {
590
    bit_width: usize,
591
    chunk_size: usize,
592
    _marker: core::marker::PhantomData<W>,
593
}
594

595
impl<W: Word> core::fmt::Display for ChunksMutError<W> {
596
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
×
597
        write!(
×
598
            f,
×
599
            "try_chunks_mut needs that the bit width ({}) times the chunk size ({}) is a multiple of W::BITS ({}) to return more than one chunk",
600
            self.bit_width,
×
601
            self.chunk_size,
×
602
            W::BITS
×
603
        )
604
    }
605
}
606

607
impl<W: Word> std::error::Error for ChunksMutError<W> {}
608

609
impl<W: Word, B: AsRef<[W]> + AsMut<[W]>> SliceByValueMut for BitFieldVec<W, B> {
610
    #[inline(always)]
611
    fn set_value(&mut self, index: usize, value: W) {
538,964✔
612
        panic_if_out_of_bounds!(index, self.len);
1,616,892✔
613
        panic_if_value!(value, self.mask, self.bit_width);
1,616,889✔
614
        unsafe {
615
            self.set_value_unchecked(index, value);
1,616,886✔
616
        }
617
    }
618

619
    unsafe fn set_value_unchecked(&mut self, index: usize, value: W) {
12,274,397✔
620
        let pos = index * self.bit_width;
24,548,794✔
621
        let word_index = pos / W::BITS;
24,548,794✔
622
        let bit_index = pos % W::BITS;
24,548,794✔
623
        let bits = self.bits.as_mut();
36,823,191✔
624

625
        unsafe {
626
            if bit_index + self.bit_width <= W::BITS {
21,534,505✔
627
                let mut word = *bits.get_unchecked_mut(word_index);
37,040,432✔
628
                word &= !(self.mask << bit_index);
27,780,324✔
629
                word |= value << bit_index;
27,780,324✔
630
                *bits.get_unchecked_mut(word_index) = word;
27,780,324✔
631
            } else {
632
                let mut word = *bits.get_unchecked_mut(word_index);
12,057,156✔
633
                word &= (W::ONE << bit_index) - W::ONE;
6,028,578✔
634
                word |= value << bit_index;
9,042,867✔
635
                *bits.get_unchecked_mut(word_index) = word;
12,057,156✔
636

637
                let mut word = *bits.get_unchecked_mut(word_index + 1);
12,057,156✔
638
                word &= !(self.mask >> (W::BITS - bit_index));
9,042,867✔
639
                word |= value >> (W::BITS - bit_index);
9,042,867✔
640
                *bits.get_unchecked_mut(word_index + 1) = word;
9,042,867✔
641
            }
642
        }
643
    }
644

645
    fn replace_value(&mut self, index: usize, value: W) -> W {
×
646
        panic_if_out_of_bounds!(index, self.len);
×
647
        panic_if_value!(value, self.mask, self.bit_width);
×
648
        unsafe { self.replace_value_unchecked(index, value) }
×
649
    }
650

651
    unsafe fn replace_value_unchecked(&mut self, index: usize, value: W) -> W {
×
652
        let pos = index * self.bit_width;
×
653
        let word_index = pos / W::BITS;
×
654
        let bit_index = pos % W::BITS;
×
655
        let bits = self.bits.as_mut();
×
656

657
        unsafe {
658
            if bit_index + self.bit_width <= W::BITS {
×
659
                let mut word = *bits.get_unchecked_mut(word_index);
×
660
                let old_value = (word >> bit_index) & self.mask;
×
661
                word &= !(self.mask << bit_index);
×
662
                word |= value << bit_index;
×
663
                *bits.get_unchecked_mut(word_index) = word;
×
664
                old_value
×
665
            } else {
666
                let mut word = *bits.get_unchecked_mut(word_index);
×
667
                let mut old_value = word >> bit_index;
×
668
                word &= (W::ONE << bit_index) - W::ONE;
×
669
                word |= value << bit_index;
×
670
                *bits.get_unchecked_mut(word_index) = word;
×
671

672
                let mut word = *bits.get_unchecked_mut(word_index + 1);
×
673
                old_value |= word << (W::BITS - bit_index);
×
674
                word &= !(self.mask >> (W::BITS - bit_index));
×
675
                word |= value >> (W::BITS - bit_index);
×
676
                *bits.get_unchecked_mut(word_index + 1) = word;
×
677
                old_value & self.mask
×
678
            }
679
        }
680
    }
681

682
    /// This implementation performs the copy word by word, which is
683
    /// significantly faster than the default implementation.
684
    fn copy(&self, from: usize, dst: &mut Self, to: usize, len: usize) {
576✔
685
        assert_eq!(
576✔
686
            self.bit_width, dst.bit_width,
×
687
            "Bit widths must be equal (self: {}, dest: {})",
×
688
            self.bit_width, dst.bit_width
×
689
        );
690
        // Reduce len to the elements available in both vectors
691
        let len = Ord::min(Ord::min(len, dst.len - to), self.len - from);
3,456✔
692
        if len == 0 {
576✔
693
            return;
×
694
        }
695
        let bit_width = Ord::min(self.bit_width, dst.bit_width);
2,304✔
696
        let bit_len = len * bit_width;
1,152✔
697
        let src_pos = from * self.bit_width;
1,152✔
698
        let dst_pos = to * dst.bit_width;
1,152✔
699
        let src_bit = src_pos % W::BITS;
1,152✔
700
        let dst_bit = dst_pos % W::BITS;
1,152✔
701
        let src_first_word = src_pos / W::BITS;
1,152✔
702
        let dst_first_word = dst_pos / W::BITS;
1,152✔
703
        let src_last_word = (src_pos + bit_len - 1) / W::BITS;
1,152✔
704
        let dst_last_word = (dst_pos + bit_len - 1) / W::BITS;
1,152✔
705
        let source = self.bits.as_ref();
1,728✔
706
        let dest = dst.bits.as_mut();
1,728✔
707

708
        if src_first_word == src_last_word && dst_first_word == dst_last_word {
768✔
709
            let mask = W::MAX >> (W::BITS - bit_len);
192✔
710
            let word = (source[src_first_word] >> src_bit) & mask;
192✔
711
            dest[dst_first_word] &= !(mask << dst_bit);
192✔
712
            dest[dst_first_word] |= word << dst_bit;
128✔
713
        } else if src_first_word == src_last_word {
640✔
714
            // dst_first_word != dst_last_word
715
            let mask = W::MAX >> (W::BITS - bit_len);
192✔
716
            let word = (source[src_first_word] >> src_bit) & mask;
192✔
717
            dest[dst_first_word] &= !(mask << dst_bit);
192✔
718
            dest[dst_first_word] |= (word & mask) << dst_bit;
192✔
719
            dest[dst_last_word] &= !(mask >> (W::BITS - dst_bit));
192✔
720
            dest[dst_last_word] |= (word & mask) >> (W::BITS - dst_bit);
128✔
721
        } else if dst_first_word == dst_last_word {
576✔
722
            // src_first_word != src_last_word
723
            let mask = W::MAX >> (W::BITS - bit_len);
192✔
724
            let word = ((source[src_first_word] >> src_bit)
256✔
725
                | (source[src_last_word] << (W::BITS - src_bit)))
128✔
726
                & mask;
128✔
727
            dest[dst_first_word] &= !(mask << dst_bit);
192✔
728
            dest[dst_first_word] |= word << dst_bit;
128✔
729
        } else if src_bit == dst_bit {
576✔
730
            // src_first_word != src_last_word && dst_first_word != dst_last_word
731
            let mask = W::MAX << dst_bit;
384✔
732
            dest[dst_first_word] &= !mask;
256✔
733
            dest[dst_first_word] |= source[src_first_word] & mask;
384✔
734

735
            dest[(1 + dst_first_word)..dst_last_word]
384✔
736
                .copy_from_slice(&source[(1 + src_first_word)..src_last_word]);
512✔
737

738
            let residual =
256✔
739
                bit_len - (W::BITS - src_bit) - (dst_last_word - dst_first_word - 1) * W::BITS;
384✔
740
            let mask = W::MAX >> (W::BITS - residual);
384✔
741
            dest[dst_last_word] &= !mask;
256✔
742
            dest[dst_last_word] |= source[src_last_word] & mask;
256✔
743
        } else if src_bit < dst_bit {
384✔
744
            // src_first_word != src_last_word && dst_first_word !=
745
            // dst_last_word
746
            let dst_mask = W::MAX << dst_bit;
256✔
747
            let src_mask = W::MAX << src_bit;
256✔
748
            let shift = dst_bit - src_bit;
256✔
749
            dest[dst_first_word] &= !dst_mask;
128✔
750
            dest[dst_first_word] |= (source[src_first_word] & src_mask) << shift;
256✔
751

752
            let mut word = source[src_first_word] >> (W::BITS - shift);
256✔
753
            for i in 1..dst_last_word - dst_first_word {
384✔
754
                dest[dst_first_word + i] = word | (source[src_first_word + i] << shift);
512✔
755
                word = source[src_first_word + i] >> (W::BITS - shift);
128✔
756
            }
757
            let residual =
128✔
758
                bit_len - (W::BITS - dst_bit) - (dst_last_word - dst_first_word - 1) * W::BITS;
256✔
759
            let mask = W::MAX >> (W::BITS - residual);
256✔
760
            dest[dst_last_word] &= !mask;
128✔
761
            dest[dst_last_word] |= source[src_last_word] & mask;
256✔
762
        } else {
763
            // src_first_word != src_last_word && dst_first_word !=
764
            // dst_last_word && src_bit > dst_bit
765
            let dst_mask = W::MAX << dst_bit;
256✔
766
            let src_mask = W::MAX << src_bit;
256✔
767
            let shift = src_bit - dst_bit;
256✔
768
            dest[dst_first_word] &= !dst_mask;
128✔
769
            dest[dst_first_word] |= (source[src_first_word] & src_mask) >> shift;
256✔
770
            dest[dst_first_word] |= source[src_first_word + 1] << (W::BITS - shift);
256✔
771

772
            let mut word = source[src_first_word + 1] >> shift;
256✔
773

774
            for i in 1..dst_last_word - dst_first_word {
1,152✔
775
                word |= source[src_first_word + i + 1] << (W::BITS - shift);
1,536✔
776
                dest[dst_first_word + i] = word;
1,024✔
777
                word = source[src_first_word + i + 1] >> shift;
512✔
778
            }
779

780
            word |= source[src_last_word] << (W::BITS - shift);
256✔
781

782
            let residual =
128✔
783
                bit_len - (W::BITS - dst_bit) - (dst_last_word - dst_first_word - 1) * W::BITS;
256✔
784
            let mask = W::MAX >> (W::BITS - residual);
256✔
785
            dest[dst_last_word] &= !mask;
128✔
786
            dest[dst_last_word] |= word & mask;
256✔
787
        }
788
    }
789

790
    /// This implementation keeps a buffer of `W::BITS` bits for reading and
791
    /// writing, obtaining a significant speedup with respect to the default
792
    /// implementation.
793
    #[inline]
794
    unsafe fn apply_in_place_unchecked<F>(&mut self, mut f: F)
×
795
    where
796
        F: FnMut(Self::Value) -> Self::Value,
797
    {
798
        if self.is_empty() {
×
799
            return;
×
800
        }
801
        let bit_width = self.bit_width();
×
802
        if bit_width == 0 {
×
803
            return;
×
804
        }
805
        let mask = self.mask();
×
806
        let number_of_words: usize = self.bits.as_ref().len();
×
807
        let last_word_idx = number_of_words.saturating_sub(1);
×
808

809
        let mut write_buffer: W = W::ZERO;
×
810
        let mut read_buffer: W = *unsafe { self.bits.as_ref().get_unchecked(0) };
×
811

812
        // specialized case because it's much faster
813
        if bit_width.is_power_of_two() {
×
814
            let mut bits_in_buffer = 0;
×
815

816
            // TODO!: figure out how to simplify
817
            let mut buffer_limit = (self.len() * bit_width) % W::BITS;
×
818
            if buffer_limit == 0 {
×
819
                buffer_limit = W::BITS;
×
820
            }
821

822
            for read_idx in 1..number_of_words {
×
823
                // pre-load the next word so it loads while we parse the buffer
824
                let next_word: W = *unsafe { self.bits.as_ref().get_unchecked(read_idx) };
×
825

826
                // parse as much as we can from the buffer
827
                loop {
×
828
                    let next_bits_in_buffer = bits_in_buffer + bit_width;
×
829

830
                    if next_bits_in_buffer > W::BITS {
×
831
                        break;
×
832
                    }
833

834
                    let value = read_buffer & mask;
×
835
                    // throw away the bits we just read
836
                    read_buffer >>= bit_width;
×
837
                    // apply user func
838
                    let new_value = f(value);
×
839
                    // put the new value in the write buffer
840
                    write_buffer |= new_value << bits_in_buffer;
×
841

842
                    bits_in_buffer = next_bits_in_buffer;
×
843
                }
844

845
                invariant_eq!(read_buffer, W::ZERO);
×
846
                *unsafe { self.bits.as_mut().get_unchecked_mut(read_idx - 1) } = write_buffer;
×
847
                read_buffer = next_word;
×
848
                write_buffer = W::ZERO;
×
849
                bits_in_buffer = 0;
×
850
            }
851

852
            // write the last word if we have some bits left
853
            while bits_in_buffer < buffer_limit {
×
854
                let value = read_buffer & mask;
×
855
                // throw away the bits we just read
856
                read_buffer >>= bit_width;
×
857
                // apply user func
858
                let new_value = f(value);
×
859
                // put the new value in the write buffer
860
                write_buffer |= new_value << bits_in_buffer;
×
861
                bits_in_buffer += bit_width;
×
862
            }
863

864
            *unsafe { self.bits.as_mut().get_unchecked_mut(last_word_idx) } = write_buffer;
×
865
            return;
×
866
        }
867

868
        // The position inside the word. In most parametrization of the
869
        // vector, since the bit_width is not necessarily an integer
870
        // divisor of the word size, we need to keep track of the position
871
        // inside the word. As we scroll through the bits, due to the bits
872
        // remainder, we may need to operate on two words at the same time.
873
        let mut global_bit_index: usize = 0;
×
874

875
        // The bit-index boundaries of the current word.
876
        let mut lower_word_limit = 0;
×
877
        let mut upper_word_limit = W::BITS;
×
878

879
        // We iterate across the words
880
        for word_number in 0..last_word_idx {
×
881
            // We iterate across the elements in the word.
882
            while global_bit_index + bit_width <= upper_word_limit {
×
883
                // We retrieve the value from the current word.
884
                let offset = global_bit_index - lower_word_limit;
×
885
                global_bit_index += bit_width;
×
886
                let element = self.mask() & (read_buffer >> offset);
×
887

888
                // We apply the function to the element.
889
                let new_element = f(element);
×
890

891
                // We set the element in the new word.
892
                write_buffer |= new_element << offset;
×
893
            }
894

895
            // We retrieve the next word from the bitvec.
896
            let next_word = *unsafe { self.bits.as_ref().get_unchecked(word_number + 1) };
×
897

898
            let mut new_write_buffer = W::ZERO;
×
899
            if upper_word_limit != global_bit_index {
×
900
                let remainder = upper_word_limit - global_bit_index;
×
901
                let offset = global_bit_index - lower_word_limit;
×
902
                // We compose the element from the remaining elements in the
903
                // current word and the elements in the next word.
904
                let element = ((read_buffer >> offset) | (next_word << remainder)) & self.mask();
×
905
                global_bit_index += bit_width;
×
906

907
                // We apply the function to the element.
908
                let new_element = f(element);
×
909

910
                write_buffer |= new_element << offset;
×
911

912
                new_write_buffer = new_element >> remainder;
×
913
            };
914

915
            read_buffer = next_word;
×
916

917
            *unsafe { self.bits.as_mut().get_unchecked_mut(word_number) } = write_buffer;
×
918

919
            write_buffer = new_write_buffer;
×
920
            lower_word_limit = upper_word_limit;
×
921
            upper_word_limit += W::BITS;
×
922
        }
923

924
        let mut offset = global_bit_index - lower_word_limit;
×
925

926
        // We iterate across the elements in the word.
927
        while offset < self.len() * bit_width - global_bit_index {
×
928
            // We retrieve the value from the current word.
929
            let element = self.mask() & (read_buffer >> offset);
×
930

931
            // We apply the function to the element.
932
            let new_element = f(element);
×
933

934
            // We set the element in the new word.
935
            write_buffer |= new_element << offset;
×
936
            offset += bit_width;
×
937
        }
938

939
        *unsafe { self.bits.as_mut().get_unchecked_mut(last_word_idx) } = write_buffer;
×
940
    }
941

942
    type ChunksMut<'a>
943
        = ChunksMut<'a, W>
944
    where
945
        Self: 'a;
946

947
    type ChunksMutError = ChunksMutError<W>;
948

949
    /// # Errors
950
    ///
951
    /// This method will return an error if the chunk size multiplied by
952
    /// the [bit width](BitWidth::bit_width) is not a multiple of
953
    /// `W::BITS` and more than one chunk must be returned.
954
    fn try_chunks_mut(
101✔
955
        &mut self,
956
        chunk_size: usize,
957
    ) -> Result<Self::ChunksMut<'_>, ChunksMutError<W>> {
958
        let len = self.len();
303✔
959
        let bit_width = self.bit_width();
303✔
960
        if len <= chunk_size || (chunk_size * bit_width) % W::BITS == 0 {
106✔
961
            Ok(ChunksMut {
99✔
962
                remaining: len,
198✔
963
                bit_width: self.bit_width,
198✔
964
                chunk_size,
198✔
965
                iter: self.bits.as_mut()[..(len * bit_width).div_ceil(W::BITS)]
297✔
966
                    .chunks_mut((chunk_size * bit_width).div_ceil(W::BITS)),
198✔
967
            })
968
        } else {
969
            Err(ChunksMutError {
2✔
970
                bit_width,
4✔
971
                chunk_size,
2✔
972
                _marker: core::marker::PhantomData,
2✔
973
            })
974
        }
975
    }
976
}
977

978
// Support for unchecked iterators
979

980
/// An [`UncheckedIterator`] over the values of a [`BitFieldVec`].
981
#[derive(Debug, Clone, MemDbg, MemSize)]
982
pub struct BitFieldVecUncheckedIter<'a, W, B>
983
where
984
    W: Word,
985
{
986
    vec: &'a BitFieldVec<W, B>,
987
    word_index: usize,
988
    window: W,
989
    fill: usize,
990
}
991

992
impl<'a, W: Word, B: AsRef<[W]>> BitFieldVecUncheckedIter<'a, W, B> {
993
    fn new(vec: &'a BitFieldVec<W, B>, index: usize) -> Self {
673,873✔
994
        if index > vec.len() {
1,347,746✔
995
            panic!("Start index out of bounds: {} > {}", index, vec.len());
×
996
        }
997
        let (fill, word_index);
×
998
        let window = if index == vec.len() {
2,021,619✔
999
            word_index = 0;
342✔
1000
            fill = 0;
342✔
1001
            W::ZERO
342✔
1002
        } else {
1003
            let bit_offset = index * vec.bit_width;
1,347,062✔
1004
            let bit_index = bit_offset % W::BITS;
1,347,062✔
1005

1006
            word_index = bit_offset / W::BITS;
673,531✔
1007
            fill = W::BITS - bit_index;
673,531✔
1008
            unsafe {
1009
                // SAFETY: index has been checked at the start and it is within bounds
1010
                *vec.bits.as_ref().get_unchecked(word_index) >> bit_index
1,347,062✔
1011
            }
1012
        };
1013
        Self {
1014
            vec,
1015
            word_index,
1016
            window,
1017
            fill,
1018
        }
1019
    }
1020
}
1021

1022
impl<W: Word, B: AsRef<[W]>> crate::traits::UncheckedIterator
1023
    for BitFieldVecUncheckedIter<'_, W, B>
1024
{
1025
    type Item = W;
1026
    unsafe fn next_unchecked(&mut self) -> W {
35,158,374✔
1027
        let bit_width = self.vec.bit_width;
70,316,748✔
1028

1029
        if self.fill >= bit_width {
35,158,374✔
1030
            self.fill -= bit_width;
19,673,846✔
1031
            let res = self.window & self.vec.mask;
39,347,692✔
1032
            self.window >>= bit_width;
19,673,846✔
1033
            return res;
19,673,846✔
1034
        }
1035

1036
        let res = self.window;
30,969,056✔
1037
        self.word_index += 1;
15,484,528✔
1038
        self.window = *unsafe { self.vec.bits.as_ref().get_unchecked(self.word_index) };
30,969,056✔
1039
        let res = (res | (self.window << self.fill)) & self.vec.mask;
46,453,584✔
1040
        let used = bit_width - self.fill;
30,969,056✔
1041
        self.window >>= used;
15,484,528✔
1042
        self.fill = W::BITS - used;
15,484,528✔
1043
        res
15,484,528✔
1044
    }
1045
}
1046

1047
impl<'a, W: Word, B: AsRef<[W]>> IntoUncheckedIterator for &'a BitFieldVec<W, B> {
1048
    type Item = W;
1049
    type IntoUncheckedIter = BitFieldVecUncheckedIter<'a, W, B>;
1050
    fn into_unchecked_iter_from(self, from: usize) -> Self::IntoUncheckedIter {
360,594✔
1051
        BitFieldVecUncheckedIter::new(self, from)
1,081,782✔
1052
    }
1053
}
1054

1055
/// An [`UncheckedIterator`] moving backwards over the values of a [`BitFieldVec`].
1056
#[derive(Debug, Clone, MemDbg, MemSize)]
1057
pub struct BitFieldVecUncheckedBackIter<'a, W: Word, B> {
1058
    vec: &'a BitFieldVec<W, B>,
1059
    word_index: usize,
1060
    window: W,
1061
    fill: usize,
1062
}
1063

1064
impl<'a, W: Word, B: AsRef<[W]>> BitFieldVecUncheckedBackIter<'a, W, B> {
1065
    fn new(vec: &'a BitFieldVec<W, B>, index: usize) -> Self {
351,147✔
1066
        if index > vec.len() {
702,294✔
1067
            panic!("Start index out of bounds: {} > {}", index, vec.len());
×
1068
        }
1069
        let (word_index, fill);
×
1070

1071
        let window = if index == 0 {
702,294✔
1072
            word_index = 0;
3,144✔
1073
            fill = 0;
3,144✔
1074
            W::ZERO
3,144✔
1075
        } else {
1076
            // We have to handle the case of zero bit width
1077
            let bit_offset = (index * vec.bit_width).saturating_sub(1);
1,044,009✔
1078
            let bit_index = bit_offset % W::BITS;
696,006✔
1079

1080
            word_index = bit_offset / W::BITS;
348,003✔
1081
            fill = bit_index + 1;
348,003✔
1082
            unsafe {
1083
                // SAFETY: index has been checked at the start and it is within bounds
1084
                *vec.bits.as_ref().get_unchecked(word_index) << (W::BITS - fill)
696,006✔
1085
            }
1086
        };
1087
        Self {
1088
            vec,
1089
            word_index,
1090
            window,
1091
            fill,
1092
        }
1093
    }
1094
}
1095

1096
impl<W: Word, B: AsRef<[W]>> crate::traits::UncheckedIterator
1097
    for BitFieldVecUncheckedBackIter<'_, W, B>
1098
{
1099
    type Item = W;
1100
    unsafe fn next_unchecked(&mut self) -> W {
18,004,593✔
1101
        let bit_width = self.vec.bit_width;
36,009,186✔
1102

1103
        if self.fill >= bit_width {
18,004,593✔
1104
            self.fill -= bit_width;
10,580,456✔
1105
            self.window = self.window.rotate_left(bit_width as u32);
21,160,912✔
1106
            return self.window & self.vec.mask;
10,580,456✔
1107
        }
1108

1109
        let mut res = self.window.rotate_left(self.fill as u32);
29,696,548✔
1110
        self.word_index -= 1;
7,424,137✔
1111
        self.window = *unsafe { self.vec.bits.as_ref().get_unchecked(self.word_index) };
14,848,274✔
1112
        let used = bit_width - self.fill;
14,848,274✔
1113
        res = ((res << used) | (self.window >> (W::BITS - used))) & self.vec.mask;
14,848,274✔
1114
        self.window <<= used;
7,424,137✔
1115
        self.fill = W::BITS - used;
7,424,137✔
1116
        res
7,424,137✔
1117
    }
1118
}
1119

1120
impl<'a, W: Word, B: AsRef<[W]>> IntoUncheckedBackIterator for &'a BitFieldVec<W, B> {
1121
    type Item = W;
1122
    type IntoUncheckedIterBack = BitFieldVecUncheckedBackIter<'a, W, B>;
1123

1124
    fn into_unchecked_iter_back(self) -> Self::IntoUncheckedIterBack {
×
1125
        BitFieldVecUncheckedBackIter::new(self, self.len())
×
1126
    }
1127

1128
    fn into_unchecked_iter_back_from(self, from: usize) -> Self::IntoUncheckedIterBack {
351,147✔
1129
        BitFieldVecUncheckedBackIter::new(self, from)
1,053,441✔
1130
    }
1131
}
1132

1133
/// An [`Iterator`] over the values of a [`BitFieldVec`].
1134
#[derive(Debug, Clone, MemDbg, MemSize)]
1135
pub struct BitFieldVecIter<'a, W, B>
1136
where
1137
    W: Word,
1138
{
1139
    unchecked: BitFieldVecUncheckedIter<'a, W, B>,
1140
    range: core::ops::Range<usize>,
1141
}
1142

1143
impl<'a, W: Word, B: AsRef<[W]>> BitFieldVecIter<'a, W, B> {
1144
    fn new(vec: &'a BitFieldVec<W, B>, from: usize) -> Self {
313,279✔
1145
        let len = vec.len();
939,837✔
1146
        if from > len {
313,279✔
NEW
1147
            panic!("Start index out of bounds: {} > {}", from, len);
×
1148
        }
1149
        Self {
1150
            unchecked: BitFieldVecUncheckedIter::new(vec, from),
1,253,116✔
1151
            range: from..len,
313,279✔
1152
        }
1153
    }
1154
}
1155

1156
impl<W: Word, B: AsRef<[W]>> Iterator for BitFieldVecIter<'_, W, B> {
1157
    type Item = W;
1158
    fn next(&mut self) -> Option<Self::Item> {
16,189,268✔
1159
        if self.range.is_empty() {
32,378,536✔
1160
            return None;
313,206✔
1161
        }
1162
        // SAFETY: index has just been checked
1163
        let res = unsafe { self.unchecked.next_unchecked() };
47,628,186✔
1164
        self.range.start += 1;
15,876,062✔
1165
        Some(res)
15,876,062✔
1166
    }
1167

1168
    #[inline(always)]
1169
    fn size_hint(&self) -> (usize, Option<usize>) {
65✔
1170
        (self.range.len(), Some(self.range.len()))
195✔
1171
    }
1172
}
1173

1174
impl<W: Word, B: AsRef<[W]>> ExactSizeIterator for BitFieldVecIter<'_, W, B> {
1175
    #[inline(always)]
1176
    fn len(&self) -> usize {
×
1177
        self.range.len()
×
1178
    }
1179
}
1180

1181
impl<W: Word, B: AsRef<[W]>> FusedIterator for BitFieldVecIter<'_, W, B> {}
1182

1183
/// This implements iteration from the end, but it's slower than the forward iteration
1184
/// as here we do a random access, while in the forward iterator we do a sequential access
1185
/// and we keep a buffer of `W::BITS` bits to speed up the iteration.
1186
///
1187
/// If needed we could also keep a buffer from the end, but the logic would be more complex
1188
/// and potentially slower.
1189
impl<W: Word, B: AsRef<[W]>> DoubleEndedIterator for BitFieldVecIter<'_, W, B> {
1190
    fn next_back(&mut self) -> Option<Self::Item> {
725✔
1191
        if self.range.is_empty() {
1,450✔
1192
            return None;
69✔
1193
        }
1194
        self.range.end -= 1;
656✔
1195
        // SAFETY: range.end was > range.start, so it is a valid index
1196
        let res = unsafe { self.unchecked.vec.get_value_unchecked(self.range.end) };
2,624✔
1197
        Some(res)
656✔
1198
    }
1199
}
1200

1201
/// Equality between bit-field vectors requires that the word is the same, the
1202
/// bit width is the same, and the content is the same.
1203
impl<W: Word, B: AsRef<[W]>, C: AsRef<[W]>> PartialEq<BitFieldVec<W, C>> for BitFieldVec<W, B> {
1204
    fn eq(&self, other: &BitFieldVec<W, C>) -> bool {
3,771✔
1205
        if self.bit_width() != other.bit_width() {
11,313✔
1206
            return false;
×
1207
        }
1208
        if self.len() != other.len() {
11,313✔
1209
            return false;
2✔
1210
        }
1211
        let bit_len = self.len() * self.bit_width();
15,076✔
1212
        if self.bits.as_ref()[..bit_len / W::BITS] != other.bits.as_ref()[..bit_len / W::BITS] {
7,538✔
1213
            return false;
×
1214
        }
1215

1216
        let residual = bit_len % W::BITS;
7,538✔
1217
        residual == 0
3,769✔
1218
            || (self.bits.as_ref()[bit_len / W::BITS] ^ other.bits.as_ref()[bit_len / W::BITS])
14,104✔
1219
                << (W::BITS - residual)
3,526✔
1220
                == W::ZERO
3,526✔
1221
    }
1222
}
1223

1224
impl<'a, W: Word, B: AsRef<[W]>> IntoIterator for &'a BitFieldVec<W, B> {
1225
    type Item = W;
1226
    type IntoIter = BitFieldVecIter<'a, W, B>;
1227

1228
    fn into_iter(self) -> Self::IntoIter {
71✔
1229
        BitFieldVecIter::new(self, 0)
142✔
1230
    }
1231
}
1232

1233
impl<'a, W: Word, B: AsRef<[W]>> IntoIteratorFrom for &'a BitFieldVec<W, B> {
1234
    type IntoIterFrom = BitFieldVecIter<'a, W, B>;
1235

1236
    fn into_iter_from(self, from: usize) -> Self::IntoIterFrom {
×
1237
        BitFieldVecIter::new(self, from)
×
1238
    }
1239
}
1240

1241
impl<W: Word> core::iter::Extend<W> for BitFieldVec<W, Vec<W>> {
1242
    fn extend<T: IntoIterator<Item = W>>(&mut self, iter: T) {
1✔
1243
        for value in iter {
17✔
1244
            self.push(value);
16✔
1245
        }
1246
    }
1247
}
1248

1249
impl<W: Word, B: AsRef<[W]>> BitFieldVec<W, B> {
1250
    pub fn iter_from(&self, from: usize) -> BitFieldVecIter<'_, W, B> {
313,208✔
1251
        BitFieldVecIter::new(self, from)
939,624✔
1252
    }
1253

1254
    pub fn iter(&self) -> BitFieldVecIter<'_, W, B> {
1,202✔
1255
        self.iter_from(0)
2,404✔
1256
    }
1257
}
1258
/// A tentatively thread-safe vector of bit fields of fixed width (AKA “compact arrays“,
1259
/// “bit array“, etc.)
1260
///
1261
/// This implementation provides some concurrency guarantees, albeit not
1262
/// full-fledged thread safety: more precisely, we can guarantee thread-safety
1263
/// if the bit width is a power of two; otherwise, concurrent writes to values
1264
/// that cross word boundaries might end up in different threads succeeding in
1265
/// writing only part of a value. If the user can guarantee that no two threads
1266
/// ever write to the same boundary-crossing value, then no race condition can
1267
/// happen.
1268
///
1269
/// See the [module documentation](crate::bits) for more details.
1270
#[derive(Debug, Clone, Hash, MemDbg, MemSize)]
1271
#[cfg_attr(feature = "epserde", derive(epserde::Epserde))]
1272
pub struct AtomicBitFieldVec<W: Word + IntoAtomic = usize, B = Vec<<W as IntoAtomic>::AtomicType>> {
1273
    /// The underlying storage.
1274
    bits: B,
1275
    /// The bit width of the values stored in the vector.
1276
    bit_width: usize,
1277
    /// A mask with its lowest `bit_width` bits set to one.
1278
    mask: W,
1279
    /// The length of the vector.
1280
    len: usize,
1281
}
1282

1283
impl<W: Word + IntoAtomic, B> AtomicBitFieldVec<W, B> {
1284
    /// # Safety
1285
    /// `len` * `bit_width` must be between 0 (included) and the number of
1286
    /// bits in `bits` (included).
1287
    #[inline(always)]
1288
    pub unsafe fn from_raw_parts(bits: B, bit_width: usize, len: usize) -> Self {
184✔
1289
        Self {
1290
            bits,
1291
            bit_width,
1292
            mask: mask(bit_width),
368✔
1293
            len,
1294
        }
1295
    }
1296

1297
    #[inline(always)]
1298
    pub fn into_raw_parts(self) -> (B, usize, usize) {
184✔
1299
        (self.bits, self.bit_width, self.len)
368✔
1300
    }
1301

1302
    /// Returns the mask used to extract values from the vector.
1303
    /// This will keep the lowest `bit_width` bits.
1304
    pub fn mask(&self) -> W {
184✔
1305
        self.mask
184✔
1306
    }
1307
}
1308

1309
impl<W: Word + IntoAtomic, B: AsRef<[W::AtomicType]>> AtomicBitFieldVec<W, B> {
1310
    /// Returns the backend of the `AtomicBitFieldVec` as a slice of `A`, where `A` is the
1311
    /// atomic variant of `W`.
1312
    pub fn as_slice(&self) -> &[W::AtomicType] {
4✔
1313
        self.bits.as_ref()
4✔
1314
    }
1315
}
1316

1317
impl<W: Word + IntoAtomic> AtomicBitFieldVec<W>
1318
where
1319
    W::AtomicType: AtomicUnsignedInt,
1320
{
1321
    pub fn new(bit_width: usize, len: usize) -> AtomicBitFieldVec<W> {
565✔
1322
        // we need at least two words to avoid branches in the gets
1323
        let n_of_words = Ord::max(1, (len * bit_width).div_ceil(W::BITS));
2,260✔
1324
        AtomicBitFieldVec::<W> {
1325
            bits: (0..n_of_words)
565✔
1326
                .map(|_| W::AtomicType::new(W::ZERO))
1327
                .collect(),
1328
            bit_width,
1329
            mask: mask(bit_width),
1,130✔
1330
            len,
1331
        }
1332
    }
1333
}
1334

1335
impl<W: Word + IntoAtomic, B> BitWidth<W::AtomicType> for AtomicBitFieldVec<W, B> {
1336
    #[inline(always)]
1337
    fn bit_width(&self) -> usize {
184✔
1338
        debug_assert!(self.bit_width <= W::BITS);
368✔
1339
        self.bit_width
184✔
1340
    }
1341
}
1342

1343
impl<W: Word + IntoAtomic, T: AsRef<[W::AtomicType]>> SliceByValue for AtomicBitFieldVec<W, T>
1344
where
1345
    W::AtomicType: AtomicUnsignedInt + AsBytes,
1346
    Self: AtomicBitFieldSlice<W>,
1347
{
1348
    type Value = W;
1349

1350
    #[inline(always)]
1351
    fn len(&self) -> usize {
×
1352
        self.len
×
1353
    }
1354

1355
    unsafe fn get_value_unchecked(&self, index: usize) -> Self::Value {
×
1356
        unsafe { self.get_atomic_unchecked(index, Ordering::Relaxed) }
×
1357
    }
1358
}
1359

1360
impl<W: Word + IntoAtomic, T: AsRef<[W::AtomicType]>> AtomicBitFieldSlice<W>
1361
    for AtomicBitFieldVec<W, T>
1362
where
1363
    W::AtomicType: AtomicUnsignedInt + AsBytes,
1364
{
1365
    #[inline]
1366
    fn len(&self) -> usize {
404,824✔
1367
        self.len
404,824✔
1368
    }
1369

1370
    #[inline]
1371
    unsafe fn get_atomic_unchecked(&self, index: usize, order: Ordering) -> W {
404,825✔
1372
        let pos = index * self.bit_width;
809,650✔
1373
        let word_index = pos / W::BITS;
809,650✔
1374
        let bit_index = pos % W::BITS;
809,650✔
1375
        let bits = self.bits.as_ref();
1,214,475✔
1376

1377
        unsafe {
1378
            if bit_index + self.bit_width <= W::BITS {
404,825✔
1379
                (bits.get_unchecked(word_index).load(order) >> bit_index) & self.mask
939,176✔
1380
            } else {
1381
                ((bits.get_unchecked(word_index).load(order) >> bit_index)
850,155✔
1382
                    | (bits.get_unchecked(word_index + 1).load(order) << (W::BITS - bit_index)))
680,124✔
1383
                    & self.mask
170,031✔
1384
            }
1385
        }
1386
    }
1387

1388
    // We reimplement set as we have the mask in the structure.
1389

1390
    /// Sets the element of the slice at the specified index.
1391
    ///
1392
    /// May panic if the index is not in [0..[len](SliceByValue::len))
1393
    /// or the value does not fit in [`BitWidth::bit_width`] bits.
1394
    #[inline(always)]
1395
    fn set_atomic(&self, index: usize, value: W, order: Ordering) {
56,026✔
1396
        panic_if_out_of_bounds!(index, self.len);
168,078✔
1397
        panic_if_value!(value, self.mask, self.bit_width);
168,075✔
1398
        unsafe {
1399
            self.set_atomic_unchecked(index, value, order);
224,096✔
1400
        }
1401
    }
1402

1403
    #[inline]
1404
    unsafe fn set_atomic_unchecked(&self, index: usize, value: W, order: Ordering) {
517,405✔
1405
        unsafe {
1406
            debug_assert!(self.bit_width <= W::BITS);
1,034,810✔
1407
            let pos = index * self.bit_width;
1,034,810✔
1408
            let word_index = pos / W::BITS;
1,034,810✔
1409
            let bit_index = pos % W::BITS;
1,034,810✔
1410
            let bits = self.bits.as_ref();
1,552,215✔
1411

1412
            if bit_index + self.bit_width <= W::BITS {
517,405✔
1413
                // this is consistent
1414
                let mut current = bits.get_unchecked(word_index).load(order);
1,489,115✔
1415
                loop {
×
1416
                    let mut new = current;
595,646✔
1417
                    new &= !(self.mask << bit_index);
595,646✔
1418
                    new |= value << bit_index;
595,646✔
1419

1420
                    match bits
893,469✔
1421
                        .get_unchecked(word_index)
595,646✔
1422
                        .compare_exchange(current, new, order, order)
1,191,292✔
1423
                    {
1424
                        Ok(_) => break,
297,823✔
1425
                        Err(e) => current = e,
×
1426
                    }
1427
                }
1428
            } else {
1429
                let mut word = bits.get_unchecked(word_index).load(order);
1,097,910✔
1430
                // try to wait for the other thread to finish
1431
                fence(Ordering::Acquire);
439,164✔
1432
                loop {
×
1433
                    let mut new = word;
439,164✔
1434
                    new &= (W::ONE << bit_index) - W::ONE;
219,582✔
1435
                    new |= value << bit_index;
439,164✔
1436

1437
                    match bits
658,746✔
1438
                        .get_unchecked(word_index)
439,164✔
1439
                        .compare_exchange(word, new, order, order)
878,328✔
1440
                    {
1441
                        Ok(_) => break,
219,582✔
1442
                        Err(e) => word = e,
×
1443
                    }
1444
                }
1445
                fence(Ordering::Release);
439,164✔
1446

1447
                // ensures that the compiler does not reorder the two atomic operations
1448
                // this should increase the probability of having consistency
1449
                // between two concurrent writes as they will both execute the set
1450
                // of the bits in the same order, and the release / acquire fence
1451
                // should try to synchronize the threads as much as possible
1452
                compiler_fence(Ordering::SeqCst);
439,164✔
1453

1454
                let mut word = bits.get_unchecked(word_index + 1).load(order);
1,097,910✔
1455
                fence(Ordering::Acquire);
439,164✔
1456
                loop {
×
1457
                    let mut new = word;
439,176✔
1458
                    new &= !(self.mask >> (W::BITS - bit_index));
439,176✔
1459
                    new |= value >> (W::BITS - bit_index);
439,176✔
1460

1461
                    match bits
658,764✔
1462
                        .get_unchecked(word_index + 1)
439,176✔
1463
                        .compare_exchange(word, new, order, order)
878,352✔
1464
                    {
1465
                        Ok(_) => break,
219,582✔
1466
                        Err(e) => word = e,
12✔
1467
                    }
1468
                }
1469
                fence(Ordering::Release);
439,164✔
1470
            }
1471
        }
1472
    }
1473

1474
    fn reset_atomic(&mut self, ordering: Ordering) {
1✔
1475
        let bit_len = self.len * self.bit_width;
2✔
1476
        let full_words = bit_len / W::BITS;
2✔
1477
        let residual = bit_len % W::BITS;
2✔
1478
        let bits = self.bits.as_ref();
3✔
1479
        bits[..full_words]
1✔
1480
            .iter()
1481
            .for_each(|x| x.store(W::ZERO, ordering));
22✔
1482
        if residual != 0 {
2✔
1483
            bits[full_words].fetch_and(W::MAX << residual, ordering);
3✔
1484
        }
1485
    }
1486

1487
    #[cfg(feature = "rayon")]
1488
    fn par_reset_atomic(&mut self, ordering: Ordering) {
1✔
1489
        let bit_len = self.len * self.bit_width;
2✔
1490
        let full_words = bit_len / W::BITS;
2✔
1491
        let residual = bit_len % W::BITS;
2✔
1492
        let bits = self.bits.as_ref();
3✔
1493
        bits[..full_words]
1✔
1494
            .par_iter()
1495
            .with_min_len(RAYON_MIN_LEN)
1✔
1496
            .for_each(|x| x.store(W::ZERO, ordering));
22✔
1497
        if residual != 0 {
2✔
1498
            bits[full_words].fetch_and(W::MAX << residual, ordering);
3✔
1499
        }
1500
    }
1501
}
1502

1503
// Conversions
1504

1505
impl<W: Word + IntoAtomic> From<AtomicBitFieldVec<W, Vec<W::AtomicType>>>
1506
    for BitFieldVec<W, Vec<W>>
1507
{
1508
    #[inline]
1509
    fn from(value: AtomicBitFieldVec<W, Vec<W::AtomicType>>) -> Self {
540✔
1510
        BitFieldVec {
1511
            bits: transmute_vec_from_atomic(value.bits),
1,620✔
1512
            len: value.len,
1,080✔
1513
            bit_width: value.bit_width,
540✔
1514
            mask: value.mask,
540✔
1515
        }
1516
    }
1517
}
1518

1519
impl<W: Word + IntoAtomic> From<AtomicBitFieldVec<W, Box<[W::AtomicType]>>>
1520
    for BitFieldVec<W, Box<[W]>>
1521
{
1522
    #[inline]
1523
    fn from(value: AtomicBitFieldVec<W, Box<[W::AtomicType]>>) -> Self {
1✔
1524
        BitFieldVec {
1525
            bits: transmute_boxed_slice_from_atomic(value.bits),
3✔
1526

1527
            len: value.len,
2✔
1528
            bit_width: value.bit_width,
1✔
1529
            mask: value.mask,
1✔
1530
        }
1531
    }
1532
}
1533

1534
impl<'a, W: Word + IntoAtomic> From<AtomicBitFieldVec<W, &'a [W::AtomicType]>>
1535
    for BitFieldVec<W, &'a [W]>
1536
{
1537
    #[inline]
1538
    fn from(value: AtomicBitFieldVec<W, &'a [W::AtomicType]>) -> Self {
1✔
1539
        BitFieldVec {
1540
            bits: unsafe { core::mem::transmute::<&'a [W::AtomicType], &'a [W]>(value.bits) },
2✔
1541
            len: value.len,
2✔
1542
            bit_width: value.bit_width,
1✔
1543
            mask: value.mask,
1✔
1544
        }
1545
    }
1546
}
1547

1548
impl<'a, W: Word + IntoAtomic> From<AtomicBitFieldVec<W, &'a mut [W::AtomicType]>>
1549
    for BitFieldVec<W, &'a mut [W]>
1550
{
1551
    #[inline]
1552
    fn from(value: AtomicBitFieldVec<W, &'a mut [W::AtomicType]>) -> Self {
1✔
1553
        BitFieldVec {
1554
            bits: unsafe {
1✔
1555
                core::mem::transmute::<&'a mut [W::AtomicType], &'a mut [W]>(value.bits)
1556
            },
1557
            len: value.len,
2✔
1558
            bit_width: value.bit_width,
1✔
1559
            mask: value.mask,
1✔
1560
        }
1561
    }
1562
}
1563

1564
impl<W: Word + IntoAtomic> From<BitFieldVec<W, Vec<W>>>
1565
    for AtomicBitFieldVec<W, Vec<W::AtomicType>>
1566
{
1567
    #[inline]
1568
    fn from(value: BitFieldVec<W, Vec<W>>) -> Self {
369✔
1569
        AtomicBitFieldVec {
1570
            bits: transmute_vec_into_atomic(value.bits),
1,107✔
1571

1572
            len: value.len,
738✔
1573
            bit_width: value.bit_width,
369✔
1574
            mask: value.mask,
369✔
1575
        }
1576
    }
1577
}
1578

1579
impl<W: Word + IntoAtomic> From<BitFieldVec<W, Box<[W]>>>
1580
    for AtomicBitFieldVec<W, Box<[W::AtomicType]>>
1581
{
1582
    #[inline]
1583
    fn from(value: BitFieldVec<W, Box<[W]>>) -> Self {
1✔
1584
        AtomicBitFieldVec {
1585
            bits: transmute_boxed_slice_into_atomic(value.bits),
3✔
1586
            len: value.len,
2✔
1587
            bit_width: value.bit_width,
1✔
1588
            mask: value.mask,
1✔
1589
        }
1590
    }
1591
}
1592

1593
impl<'a, W: Word + IntoAtomic> TryFrom<BitFieldVec<W, &'a [W]>>
1594
    for AtomicBitFieldVec<W, &'a [W::AtomicType]>
1595
{
1596
    type Error = CannotCastToAtomicError<W>;
1597

1598
    #[inline]
1599
    fn try_from(value: BitFieldVec<W, &'a [W]>) -> Result<Self, Self::Error> {
1✔
1600
        if core::mem::align_of::<W::AtomicType>() != core::mem::align_of::<W>() {
1✔
1601
            return Err(CannotCastToAtomicError::default());
×
1602
        }
1603
        Ok(AtomicBitFieldVec {
1✔
1604
            bits: unsafe { core::mem::transmute::<&'a [W], &'a [W::AtomicType]>(value.bits) },
2✔
1605
            len: value.len,
2✔
1606
            bit_width: value.bit_width,
1✔
1607
            mask: value.mask,
1✔
1608
        })
1609
    }
1610
}
1611

1612
impl<'a, W: Word + IntoAtomic> TryFrom<BitFieldVec<W, &'a mut [W]>>
1613
    for AtomicBitFieldVec<W, &'a mut [W::AtomicType]>
1614
{
1615
    type Error = CannotCastToAtomicError<W>;
1616

1617
    #[inline]
1618
    fn try_from(value: BitFieldVec<W, &'a mut [W]>) -> Result<Self, Self::Error> {
1✔
1619
        if core::mem::align_of::<W::AtomicType>() != core::mem::align_of::<W>() {
1✔
1620
            return Err(CannotCastToAtomicError::default());
×
1621
        }
1622
        Ok(AtomicBitFieldVec {
1✔
1623
            bits: unsafe {
1✔
1624
                core::mem::transmute::<&'a mut [W], &'a mut [W::AtomicType]>(value.bits)
2✔
1625
            },
1626
            len: value.len,
2✔
1627
            bit_width: value.bit_width,
1✔
1628
            mask: value.mask,
1✔
1629
        })
1630
    }
1631
}
1632

1633
impl<W: Word> From<BitFieldVec<W, Vec<W>>> for BitFieldVec<W, Box<[W]>> {
1634
    fn from(value: BitFieldVec<W, Vec<W>>) -> Self {
498✔
1635
        BitFieldVec {
1636
            bits: value.bits.into_boxed_slice(),
1,494✔
1637
            len: value.len,
996✔
1638
            bit_width: value.bit_width,
498✔
1639
            mask: value.mask,
498✔
1640
        }
1641
    }
1642
}
1643

1644
impl<W: Word> From<BitFieldVec<W, Box<[W]>>> for BitFieldVec<W, Vec<W>> {
1645
    fn from(value: BitFieldVec<W, Box<[W]>>) -> Self {
1✔
1646
        BitFieldVec {
1647
            bits: value.bits.into_vec(),
3✔
1648
            len: value.len,
2✔
1649
            bit_width: value.bit_width,
1✔
1650
            mask: value.mask,
1✔
1651
        }
1652
    }
1653
}
1654

1655
impl<'a, W: Word, B: AsRef<[W]>> value_traits::iter::IterateByValueGat<'a> for BitFieldVec<W, B> {
1656
    type Item = W;
1657
    type Iter = BitFieldVecIter<'a, W, B>;
1658
}
1659

1660
impl<W: Word, B: AsRef<[W]>> value_traits::iter::IterateByValue for BitFieldVec<W, B> {
1661
    fn iter_value(&self) -> <Self as value_traits::iter::IterateByValueGat<'_>>::Iter {
×
1662
        self.iter_from(0)
×
1663
    }
1664
}
1665

1666
impl<'a, W: Word, B: AsRef<[W]>> value_traits::iter::IterateByValueFromGat<'a>
1667
    for BitFieldVec<W, B>
1668
{
1669
    type Item = W;
1670
    type IterFrom = BitFieldVecIter<'a, W, B>;
1671
}
1672

1673
impl<W: Word, B: AsRef<[W]>> value_traits::iter::IterateByValueFrom for BitFieldVec<W, B> {
1674
    fn iter_value_from(
×
1675
        &self,
1676
        from: usize,
1677
    ) -> <Self as value_traits::iter::IterateByValueGat<'_>>::Iter {
1678
        self.iter_from(from)
×
1679
    }
1680
}
1681

1682
impl<'a, 'b, W: Word, B: AsRef<[W]>> value_traits::iter::IterateByValueGat<'a>
1683
    for BitFieldVecSubsliceImpl<'b, W, B>
1684
{
1685
    type Item = W;
1686
    type Iter = BitFieldVecIter<'a, W, B>;
1687
}
1688

1689
impl<'a, W: Word, B: AsRef<[W]>> value_traits::iter::IterateByValue
1690
    for BitFieldVecSubsliceImpl<'a, W, B>
1691
{
1692
    fn iter_value(&self) -> <Self as value_traits::iter::IterateByValueGat<'_>>::Iter {
×
1693
        self.slice.iter_from(0)
×
1694
    }
1695
}
1696

1697
impl<'a, 'b, W: Word, B: AsRef<[W]>> value_traits::iter::IterateByValueFromGat<'a>
1698
    for BitFieldVecSubsliceImpl<'b, W, B>
1699
{
1700
    type Item = W;
1701
    type IterFrom = BitFieldVecIter<'a, W, B>;
1702
}
1703

1704
impl<'a, W: Word, B: AsRef<[W]>> value_traits::iter::IterateByValueFrom
1705
    for BitFieldVecSubsliceImpl<'a, W, B>
1706
{
1707
    fn iter_value_from(
×
1708
        &self,
1709
        from: usize,
1710
    ) -> <Self as value_traits::iter::IterateByValueGat<'_>>::Iter {
1711
        self.slice.iter_from(from)
×
1712
    }
1713
}
1714

1715
impl<'a, 'b, W: Word, B: AsRef<[W]>> value_traits::iter::IterateByValueGat<'a>
1716
    for BitFieldVecSubsliceImplMut<'b, W, B>
1717
{
1718
    type Item = W;
1719
    type Iter = BitFieldVecIter<'a, W, B>;
1720
}
1721

1722
impl<'a, W: Word, B: AsRef<[W]>> value_traits::iter::IterateByValue
1723
    for BitFieldVecSubsliceImplMut<'a, W, B>
1724
{
1725
    fn iter_value(&self) -> <Self as value_traits::iter::IterateByValueGat<'_>>::Iter {
×
1726
        self.slice.iter_from(0)
×
1727
    }
1728
}
1729

1730
impl<'a, 'b, W: Word, B: AsRef<[W]>> value_traits::iter::IterateByValueFromGat<'a>
1731
    for BitFieldVecSubsliceImplMut<'b, W, B>
1732
{
1733
    type Item = W;
1734
    type IterFrom = BitFieldVecIter<'a, W, B>;
1735
}
1736

1737
impl<'a, W: Word, B: AsRef<[W]>> value_traits::iter::IterateByValueFrom
1738
    for BitFieldVecSubsliceImplMut<'a, W, B>
1739
{
1740
    fn iter_value_from(
×
1741
        &self,
1742
        from: usize,
1743
    ) -> <Self as value_traits::iter::IterateByValueGat<'_>>::Iter {
1744
        self.slice.iter_from(from)
×
1745
    }
1746
}
1747

1748
#[cfg(test)]
1749
mod tests {
1750
    use super::*;
1751

1752
    #[test]
1753
    fn test_with_capacity() {
1754
        let mut b = BitFieldVec::<usize, _>::with_capacity(10, 100);
1755
        let capacity = b.bits.capacity();
1756
        for _ in 0..100 {
1757
            b.push(0);
1758
        }
1759
        assert_eq!(b.bits.capacity(), capacity);
1760
    }
1761

1762
    fn copy<W: Word, B: AsRef<[W]>, C: AsRef<[W]> + AsMut<[W]>>(
1763
        source: &BitFieldVec<W, B>,
1764
        from: usize,
1765
        dest: &mut BitFieldVec<W, C>,
1766
        to: usize,
1767
        len: usize,
1768
    ) {
1769
        let len = Ord::min(Ord::min(len, dest.len - to), source.len - from);
1770
        for i in 0..len {
1771
            dest.set_value(to + i, source.index_value(from + i));
1772
        }
1773
    }
1774

1775
    #[test]
1776
    fn test_copy() {
1777
        for src_pattern in 0..8 {
1778
            for dst_pattern in 0..8 {
1779
                // if from_first_word == from_last_word && to_first_word == to_last_word
1780
                let source = bit_field_vec![3 => src_pattern; 100];
1781
                let mut dest_actual = bit_field_vec![3 => dst_pattern; 100];
1782
                let mut dest_expected = dest_actual.clone();
1783
                source.copy(1, &mut dest_actual, 2, 10);
1784
                copy(&source, 1, &mut dest_expected, 2, 10);
1785
                assert_eq!(dest_actual, dest_expected);
1786
                // else if from_first_word == from_last_word
1787
                let source = bit_field_vec![3 => src_pattern; 100];
1788
                let mut dest_actual = bit_field_vec![3 => dst_pattern; 100];
1789
                let mut dest_expected = dest_actual.clone();
1790
                source.copy(1, &mut dest_actual, 20, 10);
1791
                copy(&source, 1, &mut dest_expected, 20, 10);
1792
                assert_eq!(dest_actual, dest_expected);
1793
                // else if to_first_word == to_last_word
1794
                let source = bit_field_vec![3 => src_pattern; 100];
1795
                let mut dest_actual = bit_field_vec![3 => dst_pattern; 100];
1796
                let mut dest_expected = dest_actual.clone();
1797
                source.copy(20, &mut dest_actual, 1, 10);
1798
                copy(&source, 20, &mut dest_expected, 1, 10);
1799
                assert_eq!(dest_actual, dest_expected);
1800
                // else if src_bit == dest_bit (residual = 1)
1801
                let source = bit_field_vec![3 => src_pattern; 1000];
1802
                let mut dest_actual = bit_field_vec![3 => dst_pattern; 1000];
1803
                let mut dest_expected = dest_actual.clone();
1804
                source.copy(3, &mut dest_actual, 3 + 3 * 128, 40);
1805
                copy(&source, 3, &mut dest_expected, 3 + 3 * 128, 40);
1806
                assert_eq!(dest_actual, dest_expected);
1807
                // else if src_bit == dest_bit (residual = 64)
1808
                let source = bit_field_vec![3 => src_pattern; 1000];
1809
                let mut dest_actual = bit_field_vec![3 => dst_pattern; 1000];
1810
                let mut dest_expected = dest_actual.clone();
1811
                source.copy(3, &mut dest_actual, 3 + 3 * 128, 61);
1812
                copy(&source, 3, &mut dest_expected, 3 + 3 * 128, 61);
1813
                assert_eq!(dest_actual, dest_expected);
1814
                // else if src_bit < dest_bit (residual = 1)
1815
                let source = bit_field_vec![3 => src_pattern; 1000];
1816
                let mut dest_actual = bit_field_vec![3 => dst_pattern; 1000];
1817
                let mut dest_expected = dest_actual.clone();
1818
                source.copy(3, &mut dest_actual, 7 + 64 * 3, 40);
1819
                copy(&source, 3, &mut dest_expected, 7 + 64 * 3, 40);
1820
                assert_eq!(dest_actual, dest_expected);
1821
                // else if src_bit < dest_bit (residual = 64)
1822
                let source = bit_field_vec![3 => src_pattern; 1000];
1823
                let mut dest_actual = bit_field_vec![3 => dst_pattern; 1000];
1824
                let mut dest_expected = dest_actual.clone();
1825
                source.copy(3, &mut dest_actual, 7 + 64 * 3, 40 + 17);
1826
                copy(&source, 3, &mut dest_expected, 7 + 64 * 3, 40 + 17);
1827
                assert_eq!(dest_actual, dest_expected);
1828
                // else if src_bit > dest_bit (residual = 1)
1829
                let source = bit_field_vec![3 => src_pattern; 1000];
1830
                let mut dest_actual = bit_field_vec![3 => dst_pattern; 1000];
1831
                let mut dest_expected = dest_actual.clone();
1832
                source.copy(7, &mut dest_actual, 3 + 64 * 3, 40 + 64);
1833
                copy(&source, 7, &mut dest_expected, 3 + 64 * 3, 40 + 64);
1834
                assert_eq!(dest_actual, dest_expected);
1835
                // else if src_bit > dest_bit (residual = 64)
1836
                let source = bit_field_vec![3 => src_pattern; 1000];
1837
                let mut dest_actual = bit_field_vec![3 => dst_pattern; 1000];
1838
                let mut dest_expected = dest_actual.clone();
1839
                source.copy(7, &mut dest_actual, 3 + 64 * 3, 40 + 21 + 64);
1840
                copy(&source, 7, &mut dest_expected, 3 + 64 * 3, 40 + 21 + 64);
1841
                assert_eq!(dest_actual, dest_expected);
1842
            }
1843
        }
1844
    }
1845
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc