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

vigna / sux-rs / 23381386036

21 Mar 2026 02:08PM UTC coverage: 76.261% (-0.01%) from 76.275%
23381386036

push

github

vigna
Fixed test for 32 bits

5429 of 7119 relevant lines covered (76.26%)

110381855.04 hits per line

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

76.1
/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`], while for [`AtomicBitFieldVec`] it must satisfy
31
//! [`PrimitiveAtomic`] with a
32
//! [`Value`](atomic_primitive::PrimitiveAtomic::Value) satisfying [`Word`].
33
//! A blanket implementation exposes slices of elements of type `W` as bit-field
34
//! vectors of width `W::BITS`, analogously for atomic types `A`.
35
//!
36
//! The traits [`BitFieldSlice`] and [`BitFieldSliceMut`] provide a uniform
37
//! interface to access to the content of (a reference to) the bit-field vector.
38
//! There is also a [`AtomicBitFieldSlice`] trait for atomic bit-field vectors.
39
//! Since they are also implemented for slices of words, they make it easy to
40
//! write generic code that works both on bit-field vectors and on slices of
41
//! words when you need to consider the bit width of each element.
42
//!
43
//! Note that the [`try_chunks_mut`](SliceByValueMut::try_chunks_mut) method is
44
//! part of the [`SliceByValueMut`] trait, and thus returns an iterator over
45
//! elements implementing [`SliceByValueMut`]; the elements, however, implement
46
//! also [`BitFieldSliceMut`], and you can use this property by adding the bound
47
//! `for<'a> BitFieldSliceMut<ChunksMut<'a>: Iterator<Item:
48
//! BitFieldSliceMut>>`.
49
//!
50
//! Nothing is assumed about the content of the backend outside the
51
//! bits of the vector. Moreover, the content of the backend outside of the
52
//! vector is never modified by the methods of this structure.
53
//!
54
//! For high-speed unchecked scanning, we implement [`IntoUncheckedIterator`]
55
//! and [`IntoUncheckedBackIterator`] on a reference to this type. They are
56
//! used, for example, to provide
57
//! [predecessor](crate::traits::indexed_dict::Pred) and
58
//! [successor](crate::traits::indexed_dict::Succ) primitives for
59
//! [`EliasFano`].
60
//!
61
//! # Low-level support
62
//!
63
//! The methods [`addr_of`](BitFieldVec::addr_of) and
64
//! [`get_unaligned`](BitFieldVec::get_unaligned) can be used to manually
65
//! prefetch parts of the data structure, or read values using unaligned read,
66
//! when the bit width makes it possible.
67
//!
68
//! # Examples
69
//!
70
//! ```
71
//! # use sux::prelude::*;
72
//! # use bit_field_slice::*;
73
//! # use value_traits::slices::*;
74
//! // Bit field vector of bit width 5 and length 10, all entries set to zero
75
//! let mut b = <BitFieldVec<Vec<usize>>>::new(5, 10);
76
//! assert_eq!(b.len(), 10);
77
//! assert_eq!(b.bit_width(), 5);
78
//! b.set_value(0, 3);
79
//! assert_eq!(b.index_value(0), 3);
80
//!
81
//! // Empty bit field vector of bit width 20 with capacity 10
82
//! let mut b = <BitFieldVec<Vec<usize>>>::with_capacity(20, 10);
83
//! assert_eq!(b.len(), 0);
84
//! assert_eq!(b.bit_width(), 20);
85
//! b.push(20);
86
//! assert_eq!(b.len(), 1);
87
//! assert_eq!(b.index_value(0), 20);
88
//! assert_eq!(b.pop(), Some(20));
89
//!
90
//! // Convenience macro
91
//! let b = bit_field_vec![10; 4, 500, 2, 0, 1];
92
//! assert_eq!(b.len(), 5);
93
//! assert_eq!(b.bit_width(), 10);
94
//! assert_eq!(b.index_value(0), 4);
95
//! assert_eq!(b.index_value(1), 500);
96
//! assert_eq!(b.index_value(2), 2);
97
//! assert_eq!(b.index_value(3), 0);
98
//! assert_eq!(b.index_value(4), 1);
99
//! ```
100

101
use crate::prelude::{bit_field_slice::*, *};
102
use crate::traits::ambassador_impl_Backend;
103
use crate::traits::{Backend, Word};
104
use crate::utils::PrimitiveUnsignedExt;
105
use crate::utils::{
106
    CannotCastToAtomicError, transmute_boxed_slice_from_atomic, transmute_boxed_slice_into_atomic,
107
    transmute_vec_from_atomic, transmute_vec_into_atomic,
108
};
109
use crate::{panic_if_out_of_bounds, panic_if_value};
110
use ambassador::Delegate;
111
use anyhow::{Result, bail};
112
use atomic_primitive::{Atomic, AtomicPrimitive, PrimitiveAtomic, PrimitiveAtomicUnsigned};
113
use mem_dbg::*;
114
use num_primitive::{PrimitiveInteger, PrimitiveNumber};
115
#[cfg(feature = "rayon")]
116
use rayon::prelude::*;
117
use std::iter::FusedIterator;
118
use std::sync::atomic::{Ordering, compiler_fence, fence};
119
use value_traits::slices::{SliceByValue, SliceByValueMut};
120

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

192
/// A vector of bit fields of fixed width (AKA "compact array", "bit array",
193
/// etc.).
194
///
195
/// See the [module documentation](crate::bits) for more details.
196
#[derive(Debug, Clone, Copy, Hash, MemDbg, MemSize, Delegate, value_traits::Subslices)]
197
#[value_traits_subslices(bound = "B: AsRef<[B::Word]>")]
198
#[value_traits_subslices(bound = "B::Word: Word")]
199
#[derive(value_traits::SubslicesMut)]
200
#[value_traits_subslices_mut(bound = "B: AsRef<[B::Word]> + AsMut<[B::Word]>")]
201
#[value_traits_subslices_mut(bound = "B::Word: Word")]
202
#[cfg_attr(feature = "epserde", derive(epserde::Epserde))]
203
#[cfg_attr(
204
    feature = "epserde",
205
    epserde(bound(
206
        deser = "for<'a> <B as epserde::deser::DeserInner>::DeserType<'a>: Backend<Word = B::Word>"
207
    ))
208
)]
209
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
210
#[delegate(crate::traits::Backend, target = "bits")]
211
pub struct BitFieldVec<B: Backend = Vec<usize>> {
212
    /// The underlying storage.
213
    bits: B,
214
    /// The bit width of the values stored in the vector.
215
    bit_width: usize,
216
    /// A mask with its lowest `bit_width` bits set to one.
217
    mask: B::Word,
218
    /// The length of the vector.
219
    len: usize,
220
}
221

222
/// Robust, heavily checked mask function for constructors and similar methods.
223
fn mask<W: Word>(bit_width: usize) -> W {
5,743✔
224
    if bit_width == 0 {
5,743✔
225
        W::ZERO
158✔
226
    } else {
227
        W::MAX
5,585✔
228
            >> (W::BITS as usize)
11,170✔
229
                .checked_sub(bit_width)
16,755✔
230
                .expect("bit_width > W::BITS as usize")
5,585✔
231
    }
232
}
233

234
impl<B: Backend<Word: Word>> BitFieldVec<B> {
235
    /// # Safety
236
    /// `len` * `bit_width` must be between 0 (included) and the number of
237
    /// bits in `bits` (included).
238
    #[inline(always)]
239
    pub unsafe fn from_raw_parts(bits: B, bit_width: usize, len: usize) -> Self {
3,223✔
240
        Self {
241
            bits,
242
            bit_width,
243
            mask: mask(bit_width),
6,446✔
244
            len,
245
        }
246
    }
247

248
    /// Returns the backend, the bit width, and the length, consuming this
249
    /// vector.
250
    #[inline(always)]
251
    pub fn into_raw_parts(self) -> (B, usize, usize) {
3,122✔
252
        (self.bits, self.bit_width, self.len)
6,244✔
253
    }
254

255
    /// Replaces the backend by applying a function, consuming this vector.
256
    ///
257
    /// # Safety
258
    /// The caller must ensure that the length is compatible with the new
259
    /// backend.
260
    #[inline(always)]
261
    pub unsafe fn map<B2: Backend<Word: Word>>(self, f: impl FnOnce(B) -> B2) -> BitFieldVec<B2> {
×
262
        BitFieldVec {
263
            bits: f(self.bits),
×
264
            bit_width: self.bit_width,
×
265
            mask: mask(self.bit_width),
×
266
            len: self.len,
×
267
        }
268
    }
269
}
270

271
impl<B: Backend<Word: Word> + AsRef<[B::Word]>> BitFieldVec<B> {
272
    /// Gets the address of the item storing (the first part of)
273
    /// the element of given index.
274
    ///
275
    /// This method is mainly useful for manually prefetching
276
    /// parts of the data structure.
277
    pub fn addr_of(&self, index: usize) -> *const B::Word {
4✔
278
        let start_bit = index * self.bit_width;
8✔
279
        let word_index = start_bit / B::Word::BITS as usize;
8✔
280
        (&self.bits.as_ref()[word_index]) as *const _
8✔
281
    }
282

283
    /// Like [`SliceByValue::index_value`], but using unaligned reads.
284
    ///
285
    /// This method can be used only for bit width smaller than or equal to
286
    /// `W::BITS as usize - 8 + 2` or equal to `W::BITS as usize - 8 + 4` or `W::BITS`. Moreover,
287
    /// an additional padding word must be present at the end of the vector.
288
    ///
289
    /// Note that to guarantee the absence of undefined behavior this method
290
    /// has to perform several tests. Consider using
291
    /// [`get_unaligned_unchecked`](Self::get_unaligned_unchecked) if you are
292
    /// sure that the constraints are respected.
293
    ///
294
    /// # Panics
295
    ///
296
    /// This method will panic if the constraints above are not respected.
297
    pub fn get_unaligned(&self, index: usize) -> B::Word {
65✔
298
        let bits = B::Word::BITS as usize;
130✔
299
        assert!(
65✔
300
            self.bit_width <= bits - 8 + 2
65✔
301
                || self.bit_width == bits - 8 + 4
24✔
302
                || self.bit_width == bits
14✔
303
        );
304
        panic_if_out_of_bounds!(index, self.len);
183✔
305
        assert!(
61✔
306
            (index * self.bit_width) / size_of::<B::Word>() + size_of::<B::Word>()
122✔
307
                <= std::mem::size_of_val(self.bits.as_ref())
122✔
308
        );
309
        unsafe { self.get_unaligned_unchecked(index) }
180✔
310
    }
311

312
    /// Like [`SliceByValue::get_value_unchecked`], but using unaligned reads.
313
    ///
314
    /// # Safety
315
    ///
316
    /// This method can be used only for bit width smaller than or equal to
317
    /// `W::BITS as usize - 8 + 2` or equal to `W::BITS as usize - 8 + 4` or `W::BITS`. Moreover,
318
    /// an additional padding word must be present at the end of the vector.
319
    ///
320
    /// # Panics
321
    ///
322
    /// This method will panic in debug mode if the safety constraints are not
323
    /// respected.
324
    pub unsafe fn get_unaligned_unchecked(&self, index: usize) -> B::Word {
65✔
325
        let bits = B::Word::BITS as usize;
130✔
326
        debug_assert!(
65✔
327
            self.bit_width <= bits - 8 + 2
65✔
328
                || self.bit_width == bits - 8 + 4
24✔
329
                || self.bit_width == bits
14✔
330
        );
331
        let base_ptr = self.bits.as_ref().as_ptr() as *const u8;
122✔
332
        let start_bit = index * self.bit_width;
122✔
333
        debug_assert!(
61✔
334
            start_bit / size_of::<B::Word>() + size_of::<B::Word>()
122✔
335
                <= std::mem::size_of_val(self.bits.as_ref())
122✔
336
        );
337
        let ptr = unsafe { base_ptr.add(start_bit / 8) } as *const B::Word;
240✔
338
        let word = unsafe { core::ptr::read_unaligned(ptr) };
180✔
339
        (word >> (start_bit % 8)) & self.mask
60✔
340
    }
341

342
    /// Returns the backend of the vector as a slice of words.
343
    pub fn as_slice(&self) -> &[B::Word] {
3✔
344
        self.bits.as_ref()
3✔
345
    }
346
}
347
/// An iterator over non-overlapping chunks of a bit-field vector, starting at
348
/// the beginning of the vector.
349
///
350
/// When the vector len is not evenly divided by the chunk size, the last chunk
351
/// of the iteration will be shorter.
352
///
353
/// This struct is created by the
354
/// [`try_chunks_mut`](crate::bits::bit_field_vec::BitFieldVec#impl-BitFieldSliceMut-for-BitFieldVec<B>)
355
/// method.
356
pub struct ChunksMut<'a, W: Word> {
357
    remaining: usize,
358
    bit_width: usize,
359
    chunk_size: usize,
360
    iter: std::slice::ChunksMut<'a, W>,
361
}
362

363
impl<'a, W: Word> Iterator for ChunksMut<'a, W> {
364
    type Item = BitFieldVec<&'a mut [W]>;
365

366
    #[inline]
367
    fn next(&mut self) -> Option<Self::Item> {
104✔
368
        self.iter.next().map(|chunk| {
415✔
369
            let size = Ord::min(self.chunk_size, self.remaining);
412✔
370
            let next = unsafe { BitFieldVec::from_raw_parts(chunk, self.bit_width, size) };
515✔
371
            self.remaining -= size;
103✔
372
            next
103✔
373
        })
374
    }
375
}
376

377
impl<'a, W: Word> ExactSizeIterator for ChunksMut<'a, W> where
378
    std::slice::ChunksMut<'a, W>: ExactSizeIterator
379
{
380
}
381

382
impl<'a, W: Word> FusedIterator for ChunksMut<'a, W> where
383
    std::slice::ChunksMut<'a, W>: FusedIterator
384
{
385
}
386

387
impl<B: Backend<Word: Word> + AsRef<[B::Word]>> BitFieldVec<B> {}
388

389
impl<W: Word> BitFieldVec<Vec<W>> {
390
    /// Creates a new zero-initialized vector of given bit width and length.
391
    pub fn new(bit_width: usize, len: usize) -> Self {
867✔
392
        // We need at least one word to handle the case of bit width zero.
393
        let n_of_words = Ord::max(1, (len * bit_width).div_ceil(W::BITS as usize));
4,335✔
394
        Self {
395
            bits: vec![W::ZERO; n_of_words],
2,601✔
396
            bit_width,
397
            mask: mask(bit_width),
1,734✔
398
            len,
399
        }
400
    }
401

402
    /// Creates a new zero-initialized vector of given bit width and length,
403
    /// adding padding bits to the end of the vector so that unaligned reads are
404
    /// possible.
405
    ///
406
    /// Note that this convenience method is a one-off: if the vector is resized
407
    /// or expanded, the padding will be lost.
408
    pub fn new_unaligned(bit_width: usize, len: usize) -> Self {
103✔
409
        let n_of_words = (len * bit_width).div_ceil(W::BITS as usize);
412✔
410
        Self {
411
            // We add a word at the end
412
            bits: vec![W::ZERO; n_of_words + 1],
309✔
413
            bit_width,
414
            mask: mask(bit_width),
206✔
415
            len,
416
        }
417
    }
418

419
    /// Creates an empty vector that doesn't need to reallocate for up to
420
    /// `capacity` elements.
421
    pub fn with_capacity(bit_width: usize, capacity: usize) -> Self {
1,166✔
422
        // We need at least one word to handle the case of bit width zero.
423
        let n_of_words = Ord::max(1, (capacity * bit_width).div_ceil(W::BITS as usize));
5,830✔
424
        Self {
425
            bits: Vec::with_capacity(n_of_words),
3,498✔
426
            bit_width,
427
            mask: mask(bit_width),
1,166✔
428
            len: 0,
429
        }
430
    }
431

432
    /// Sets the length.
433
    ///
434
    /// # Safety
435
    ///
436
    /// `len * bit_width` must be at most `self.bits.len() * W::BITS as usize`. Note that
437
    /// setting the length might result in reading uninitialized data.
438
    pub unsafe fn set_len(&mut self, len: usize) {
1✔
439
        debug_assert!(len * self.bit_width <= self.bits.len() * W::BITS as usize);
4✔
440
        self.len = len;
1✔
441
    }
442

443
    /// Sets len to 0.
444
    pub fn clear(&mut self) {
1✔
445
        self.len = 0;
1✔
446
    }
447

448
    /// Returns the bit width of the values inside the vector.
449
    pub const fn bit_width(&self) -> usize {
439✔
450
        debug_assert!(self.bit_width <= W::BITS as usize);
878✔
451
        self.bit_width
439✔
452
    }
453

454
    /// Returns the mask used to extract values from the vector.
455
    /// This will keep the lowest `bit_width` bits.
456
    pub const fn mask(&self) -> W {
312✔
457
        self.mask
312✔
458
    }
459

460
    /// Creates a new vector by copying a slice; the bit width will be the minimum
461
    /// width sufficient to hold all values in the slice.
462
    ///
463
    /// Returns an error if the bit width of the values in `slice` is larger than
464
    /// `W::BITS`.
465
    pub fn from_slice<S: BitFieldSlice<Value: Word + num_primitive::PrimitiveNumberAs<W>>>(
3✔
466
        slice: &S,
467
    ) -> Result<Self> {
468
        let mut max_len: usize = 0;
9✔
469
        for i in 0..slice.len() {
6,003✔
470
            max_len = Ord::max(max_len, unsafe {
9,000✔
471
                slice.get_value_unchecked(i).bit_len() as usize
9,000✔
472
            });
473
        }
474

475
        if max_len > W::BITS as usize {
3✔
476
            bail!(
1✔
477
                "Cannot convert a slice of bit width {} into a slice with W = {}",
×
478
                max_len,
×
479
                std::any::type_name::<W>()
1✔
480
            );
481
        }
482
        let mut result = Self::new(max_len, slice.len());
10✔
483
        for i in 0..slice.len() {
4,002✔
484
            unsafe { result.set_value_unchecked(i, slice.get_value_unchecked(i).as_to::<W>()) };
12,000✔
485
        }
486

487
        Ok(result)
2✔
488
    }
489

490
    /// Adds a value at the end of the vector.
491
    pub fn push(&mut self, value: W) {
2,419✔
492
        panic_if_value!(value, self.mask, self.bit_width);
7,257✔
493
        if (self.len + 1) * self.bit_width > self.bits.len() * W::BITS as usize {
7,658✔
494
            self.bits.push(W::ZERO);
401✔
495
        }
496
        unsafe {
497
            self.set_value_unchecked(self.len, value);
7,257✔
498
        }
499
        self.len += 1;
2,419✔
500
    }
501

502
    /// Truncates or extends with `value` the vector.
503
    pub fn resize(&mut self, new_len: usize, value: W) {
1,162✔
504
        panic_if_value!(value, self.mask, self.bit_width);
3,486✔
505
        if new_len > self.len {
1,162✔
506
            if new_len * self.bit_width > self.bits.len() * W::BITS as usize {
4,644✔
507
                self.bits.resize(
3,483✔
508
                    (new_len * self.bit_width).div_ceil(W::BITS as usize),
2,322✔
509
                    W::ZERO,
1,161✔
510
                );
511
            }
512
            for i in self.len..new_len {
807,721✔
513
                unsafe {
514
                    self.set_value_unchecked(i, value);
2,419,680✔
515
                }
516
            }
517
        }
518
        self.len = new_len;
1,162✔
519
    }
520

521
    /// Removes and returns a value from the end of the vector.
522
    ///
523
    /// Returns None if the [`BitFieldVec`] is empty.
524
    pub fn pop(&mut self) -> Option<W> {
1,002✔
525
        if self.len == 0 {
1,002✔
526
            return None;
2✔
527
        }
528
        let value = self.index_value(self.len - 1);
4,000✔
529
        self.len -= 1;
1,000✔
530
        Some(value)
1,000✔
531
    }
532
}
533

534
impl<B: Backend<Word: Word> + AsRef<[B::Word]> + AsMut<[B::Word]>> BitFieldVec<B> {}
535

536
impl<B: Backend<Word: Word>> BitWidth for BitFieldVec<B> {
537
    #[inline(always)]
538
    fn bit_width(&self) -> usize {
11,536✔
539
        debug_assert!(self.bit_width <= B::Word::BITS as usize);
23,072✔
540
        self.bit_width
11,536✔
541
    }
542
}
543

544
impl<B: Backend<Word: Word> + AsRef<[B::Word]>> SliceByValue for BitFieldVec<B> {
545
    type Value = B::Word;
546
    #[inline(always)]
547
    fn len(&self) -> usize {
1,241,338✔
548
        self.len
1,241,338✔
549
    }
550

551
    unsafe fn get_value_unchecked(&self, index: usize) -> B::Word {
52,713,505✔
552
        let bits = B::Word::BITS as usize;
105,427,010✔
553
        let pos = index * self.bit_width;
105,427,010✔
554
        let word_index = pos / bits;
105,427,010✔
555
        let bit_index = pos % bits;
105,427,010✔
556
        let data = self.bits.as_ref();
158,140,515✔
557

558
        unsafe {
559
            if bit_index + self.bit_width <= bits {
52,713,505✔
560
                (*data.get_unchecked(word_index) >> bit_index) & self.mask
78,962,172✔
561
            } else {
562
                ((*data.get_unchecked(word_index) >> bit_index)
39,697,257✔
563
                    | (*data.get_unchecked(word_index + 1) << (bits - bit_index)))
39,697,257✔
564
                    & self.mask
13,232,419✔
565
            }
566
        }
567
    }
568
}
569

570
impl<B: Backend<Word: Word> + AsRef<[B::Word]>> BitFieldSlice for BitFieldVec<B> {
571
    fn as_slice(&self) -> &[Self::Value] {
×
572
        self.bits.as_ref()
×
573
    }
574
}
575

576
impl<B: Backend<Word: Word> + AsRef<[B::Word]> + AsMut<[B::Word]>> BitFieldSliceMut
577
    for BitFieldVec<B>
578
{
579
    fn reset(&mut self) {
1✔
580
        let bit_len = self.len * self.bit_width;
2✔
581
        let full_words = bit_len / B::Word::BITS as usize;
2✔
582
        let residual = bit_len % B::Word::BITS as usize;
2✔
583
        let bits = self.bits.as_mut();
3✔
584
        bits[..full_words]
1✔
585
            .iter_mut()
586
            .for_each(|x| *x = B::Word::ZERO);
1✔
587
        if residual != 0 {
2✔
588
            bits[full_words] &= B::Word::MAX << residual;
1✔
589
        }
590
    }
591

592
    #[cfg(feature = "rayon")]
593
    fn par_reset(&mut self) {
1✔
594
        let bit_len = self.len * self.bit_width;
2✔
595
        let full_words = bit_len / B::Word::BITS as usize;
2✔
596
        let residual = bit_len % B::Word::BITS as usize;
2✔
597
        let bits = self.bits.as_mut();
3✔
598
        bits[..full_words]
1✔
599
            .par_iter_mut()
600
            .with_min_len(crate::RAYON_MIN_LEN)
1✔
601
            .for_each(|x| *x = B::Word::ZERO);
1✔
602
        if residual != 0 {
2✔
603
            bits[full_words] &= B::Word::MAX << residual;
1✔
604
        }
605
    }
606

607
    fn as_mut_slice(&mut self) -> &mut [B::Word] {
1✔
608
        self.bits.as_mut()
1✔
609
    }
610
}
611

612
/// Error type returned when [`try_chunks_mut`](SliceByValueMut::try_chunks_mut)
613
/// does not find sufficient alignment.
614
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
615
pub struct ChunksMutError<W: Word> {
616
    bit_width: usize,
617
    chunk_size: usize,
618
    _marker: core::marker::PhantomData<W>,
619
}
620

621
impl<W: Word> core::fmt::Display for ChunksMutError<W> {
622
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
×
623
        write!(
×
624
            f,
×
625
            "try_chunks_mut needs that the bit width ({}) times the chunk size ({}) is a multiple of W::BITS ({}) to return more than one chunk",
626
            self.bit_width,
×
627
            self.chunk_size,
×
628
            W::BITS as usize
×
629
        )
630
    }
631
}
632

633
impl<W: Word> std::error::Error for ChunksMutError<W> {}
634

635
impl<B: Backend<Word: Word> + AsRef<[B::Word]> + AsMut<[B::Word]>> SliceByValueMut
636
    for BitFieldVec<B>
637
{
638
    #[inline(always)]
639
    fn set_value(&mut self, index: usize, value: B::Word) {
483,233✔
640
        panic_if_out_of_bounds!(index, self.len);
1,449,699✔
641
        panic_if_value!(value, self.mask, self.bit_width);
1,449,696✔
642
        unsafe {
643
            self.set_value_unchecked(index, value);
1,449,693✔
644
        }
645
    }
646

647
    unsafe fn set_value_unchecked(&mut self, index: usize, value: B::Word) {
11,883,836✔
648
        let bits = B::Word::BITS as usize;
23,767,672✔
649
        let pos = index * self.bit_width;
23,767,672✔
650
        let word_index = pos / bits;
23,767,672✔
651
        let bit_index = pos % bits;
23,767,672✔
652
        let data = self.bits.as_mut();
35,651,508✔
653

654
        unsafe {
655
            if bit_index + self.bit_width <= bits {
20,894,296✔
656
                let mut word = *data.get_unchecked_mut(word_index);
36,041,840✔
657
                word &= !(self.mask << bit_index);
27,031,380✔
658
                word |= value << bit_index;
27,031,380✔
659
                *data.get_unchecked_mut(word_index) = word;
27,031,380✔
660
            } else {
661
                let mut word = *data.get_unchecked_mut(word_index);
11,493,504✔
662
                word &= (B::Word::ONE << bit_index) - B::Word::ONE;
5,746,752✔
663
                word |= value << bit_index;
8,620,128✔
664
                *data.get_unchecked_mut(word_index) = word;
11,493,504✔
665

666
                let mut word = *data.get_unchecked_mut(word_index + 1);
11,493,504✔
667
                word &= !(self.mask >> (bits - bit_index));
11,493,504✔
668
                word |= value >> (bits - bit_index);
11,493,504✔
669
                *data.get_unchecked_mut(word_index + 1) = word;
8,620,128✔
670
            }
671
        }
672
    }
673

674
    fn replace_value(&mut self, index: usize, value: B::Word) -> B::Word {
×
675
        panic_if_out_of_bounds!(index, self.len);
×
676
        panic_if_value!(value, self.mask, self.bit_width);
×
677
        unsafe { self.replace_value_unchecked(index, value) }
×
678
    }
679

680
    unsafe fn replace_value_unchecked(&mut self, index: usize, value: B::Word) -> B::Word {
×
681
        let bits = B::Word::BITS as usize;
×
682
        let pos = index * self.bit_width;
×
683
        let word_index = pos / bits;
×
684
        let bit_index = pos % bits;
×
685
        let data = self.bits.as_mut();
×
686

687
        unsafe {
688
            if bit_index + self.bit_width <= bits {
×
689
                let mut word = *data.get_unchecked_mut(word_index);
×
690
                let old_value = (word >> bit_index) & self.mask;
×
691
                word &= !(self.mask << bit_index);
×
692
                word |= value << bit_index;
×
693
                *data.get_unchecked_mut(word_index) = word;
×
694
                old_value
×
695
            } else {
696
                let mut word = *data.get_unchecked_mut(word_index);
×
697
                let mut old_value = word >> bit_index;
×
698
                word &= (B::Word::ONE << bit_index) - B::Word::ONE;
×
699
                word |= value << bit_index;
×
700
                *data.get_unchecked_mut(word_index) = word;
×
701

702
                let mut word = *data.get_unchecked_mut(word_index + 1);
×
703
                old_value |= word << (bits - bit_index);
×
704
                word &= !(self.mask >> (bits - bit_index));
×
705
                word |= value >> (bits - bit_index);
×
706
                *data.get_unchecked_mut(word_index + 1) = word;
×
707
                old_value & self.mask
×
708
            }
709
        }
710
    }
711

712
    /// This implementation performs the copy word by word, which is
713
    /// significantly faster than the default implementation.
714
    fn copy(&self, from: usize, dst: &mut Self, to: usize, len: usize) {
576✔
715
        assert_eq!(
576✔
716
            self.bit_width, dst.bit_width,
×
717
            "Bit widths must be equal (self: {}, dest: {})",
×
718
            self.bit_width, dst.bit_width
×
719
        );
720
        // Reduce len to the elements available in both vectors
721
        let len = Ord::min(Ord::min(len, dst.len - to), self.len - from);
3,456✔
722
        if len == 0 {
576✔
723
            return;
×
724
        }
725
        let bit_width = Ord::min(self.bit_width, dst.bit_width);
2,304✔
726
        let bit_len = len * bit_width;
1,152✔
727
        let src_pos = from * self.bit_width;
1,152✔
728
        let dst_pos = to * dst.bit_width;
1,152✔
729
        let bits = B::Word::BITS as usize;
1,152✔
730
        let src_bit = src_pos % bits;
1,152✔
731
        let dst_bit = dst_pos % bits;
1,152✔
732
        let src_first_word = src_pos / bits;
1,152✔
733
        let dst_first_word = dst_pos / bits;
1,152✔
734
        let src_last_word = (src_pos + bit_len - 1) / bits;
1,152✔
735
        let dst_last_word = (dst_pos + bit_len - 1) / bits;
1,152✔
736
        let source = self.bits.as_ref();
1,728✔
737
        let dest = dst.bits.as_mut();
1,728✔
738

739
        if src_first_word == src_last_word && dst_first_word == dst_last_word {
768✔
740
            let mask = B::Word::MAX >> (bits - bit_len);
192✔
741
            let word = (source[src_first_word] >> src_bit) & mask;
192✔
742
            dest[dst_first_word] &= !(mask << dst_bit);
192✔
743
            dest[dst_first_word] |= word << dst_bit;
128✔
744
        } else if src_first_word == src_last_word {
640✔
745
            // dst_first_word != dst_last_word
746
            let mask = B::Word::MAX >> (bits - bit_len);
192✔
747
            let word = (source[src_first_word] >> src_bit) & mask;
192✔
748
            dest[dst_first_word] &= !(mask << dst_bit);
192✔
749
            dest[dst_first_word] |= (word & mask) << dst_bit;
192✔
750
            dest[dst_last_word] &= !(mask >> (bits - dst_bit));
256✔
751
            dest[dst_last_word] |= (word & mask) >> (bits - dst_bit);
192✔
752
        } else if dst_first_word == dst_last_word {
576✔
753
            // src_first_word != src_last_word
754
            let mask = B::Word::MAX >> (bits - bit_len);
192✔
755
            let word = ((source[src_first_word] >> src_bit)
256✔
756
                | (source[src_last_word] << (bits - src_bit)))
192✔
757
                & mask;
128✔
758
            dest[dst_first_word] &= !(mask << dst_bit);
192✔
759
            dest[dst_first_word] |= word << dst_bit;
128✔
760
        } else if src_bit == dst_bit {
576✔
761
            // src_first_word != src_last_word && dst_first_word != dst_last_word
762
            let mask = B::Word::MAX << dst_bit;
384✔
763
            dest[dst_first_word] &= !mask;
256✔
764
            dest[dst_first_word] |= source[src_first_word] & mask;
384✔
765

766
            dest[(1 + dst_first_word)..dst_last_word]
384✔
767
                .copy_from_slice(&source[(1 + src_first_word)..src_last_word]);
512✔
768

769
            let residual = bit_len - (bits - src_bit) - (dst_last_word - dst_first_word - 1) * bits;
640✔
770
            let mask = B::Word::MAX >> (bits - residual);
384✔
771
            dest[dst_last_word] &= !mask;
256✔
772
            dest[dst_last_word] |= source[src_last_word] & mask;
256✔
773
        } else if src_bit < dst_bit {
384✔
774
            // src_first_word != src_last_word && dst_first_word !=
775
            // dst_last_word
776
            let dst_mask = B::Word::MAX << dst_bit;
256✔
777
            let src_mask = B::Word::MAX << src_bit;
256✔
778
            let shift = dst_bit - src_bit;
256✔
779
            dest[dst_first_word] &= !dst_mask;
128✔
780
            dest[dst_first_word] |= (source[src_first_word] & src_mask) << shift;
256✔
781

782
            let mut word = source[src_first_word] >> (bits - shift);
384✔
783
            for i in 1..dst_last_word - dst_first_word {
384✔
784
                dest[dst_first_word + i] = word | (source[src_first_word + i] << shift);
512✔
785
                word = source[src_first_word + i] >> (bits - shift);
256✔
786
            }
787
            let residual = bit_len - (bits - dst_bit) - (dst_last_word - dst_first_word - 1) * bits;
512✔
788
            let mask = B::Word::MAX >> (bits - residual);
256✔
789
            dest[dst_last_word] &= !mask;
128✔
790
            dest[dst_last_word] |= (word | (source[src_last_word] << shift)) & mask;
384✔
791
        } else {
792
            // src_first_word != src_last_word && dst_first_word !=
793
            // dst_last_word && src_bit > dst_bit
794
            let dst_mask = B::Word::MAX << dst_bit;
256✔
795
            let src_mask = B::Word::MAX << src_bit;
256✔
796
            let shift = src_bit - dst_bit;
256✔
797
            dest[dst_first_word] &= !dst_mask;
128✔
798
            dest[dst_first_word] |= (source[src_first_word] & src_mask) >> shift;
256✔
799
            dest[dst_first_word] |= source[src_first_word + 1] << (bits - shift);
384✔
800

801
            let mut word = source[src_first_word + 1] >> shift;
256✔
802

803
            for i in 1..dst_last_word - dst_first_word {
1,152✔
804
                word |= source[src_first_word + i + 1] << (bits - shift);
2,048✔
805
                dest[dst_first_word + i] = word;
1,024✔
806
                word = source[src_first_word + i + 1] >> shift;
512✔
807
            }
808

809
            word |= source[src_last_word] << (bits - shift);
384✔
810

811
            let residual = bit_len - (bits - dst_bit) - (dst_last_word - dst_first_word - 1) * bits;
512✔
812
            let mask = B::Word::MAX >> (bits - residual);
256✔
813
            dest[dst_last_word] &= !mask;
128✔
814
            dest[dst_last_word] |= word & mask;
256✔
815
        }
816
    }
817

818
    /// This implementation keeps a buffer of `W::BITS` bits for reading and
819
    /// writing, obtaining a significant speedup with respect to the default
820
    /// implementation.
821
    #[inline]
822
    unsafe fn apply_in_place_unchecked<F>(&mut self, mut f: F)
×
823
    where
824
        F: FnMut(Self::Value) -> Self::Value,
825
    {
826
        if self.is_empty() {
×
827
            return;
×
828
        }
829
        let bit_width = self.bit_width();
×
830
        if bit_width == 0 {
×
831
            return;
×
832
        }
833
        let mask = self.mask;
×
834
        let number_of_words: usize = self.bits.as_ref().len();
×
835
        let last_word_idx = number_of_words.saturating_sub(1);
×
836

837
        let bits = B::Word::BITS as usize;
×
838
        let mut write_buffer: B::Word = B::Word::ZERO;
×
839
        let mut read_buffer: B::Word = *unsafe { self.bits.as_ref().get_unchecked(0) };
×
840

841
        // specialized case because it's much faster
842
        if bit_width.is_power_of_two() {
×
843
            let mut bits_in_buffer = 0;
×
844

845
            let mut buffer_limit = (self.len() * bit_width) % bits;
×
846
            if buffer_limit == 0 {
×
847
                buffer_limit = bits;
×
848
            }
849

850
            for read_idx in 1..number_of_words {
×
851
                // pre-load the next word so it loads while we parse the buffer
852
                let next_word: B::Word = *unsafe { self.bits.as_ref().get_unchecked(read_idx) };
×
853

854
                // parse as much as we can from the buffer
855
                loop {
×
856
                    let next_bits_in_buffer = bits_in_buffer + bit_width;
×
857

858
                    if next_bits_in_buffer > bits {
×
859
                        break;
×
860
                    }
861

862
                    let value = read_buffer & mask;
×
863
                    // throw away the bits we just read
864
                    read_buffer >>= bit_width;
×
865
                    // apply user func
866
                    let new_value = f(value);
×
867
                    // put the new value in the write buffer
868
                    write_buffer |= new_value << bits_in_buffer;
×
869

870
                    bits_in_buffer = next_bits_in_buffer;
×
871
                }
872

873
                debug_assert_eq!(read_buffer, B::Word::ZERO);
×
874
                *unsafe { self.bits.as_mut().get_unchecked_mut(read_idx - 1) } = write_buffer;
×
875
                read_buffer = next_word;
×
876
                write_buffer = B::Word::ZERO;
×
877
                bits_in_buffer = 0;
×
878
            }
879

880
            // write the last word if we have some bits left
881
            while bits_in_buffer < buffer_limit {
×
882
                let value = read_buffer & mask;
×
883
                // throw away the bits we just read
884
                read_buffer >>= bit_width;
×
885
                // apply user func
886
                let new_value = f(value);
×
887
                // put the new value in the write buffer
888
                write_buffer |= new_value << bits_in_buffer;
×
889
                bits_in_buffer += bit_width;
×
890
            }
891

892
            *unsafe { self.bits.as_mut().get_unchecked_mut(last_word_idx) } = write_buffer;
×
893
            return;
×
894
        }
895

896
        // The position inside the word. In most parametrization of the
897
        // vector, since the bit_width is not necessarily an integer
898
        // divisor of the word size, we need to keep track of the position
899
        // inside the word. As we scroll through the bits, due to the bits
900
        // remainder, we may need to operate on two words at the same time.
901
        let mut global_bit_index: usize = 0;
×
902

903
        // The bit-index boundaries of the current word.
904
        let mut lower_word_limit = 0;
×
905
        let mut upper_word_limit = bits;
×
906

907
        // We iterate across the words
908
        for word_number in 0..last_word_idx {
×
909
            // We iterate across the elements in the word.
910
            while global_bit_index + bit_width <= upper_word_limit {
×
911
                // We retrieve the value from the current word.
912
                let offset = global_bit_index - lower_word_limit;
×
913
                global_bit_index += bit_width;
×
914
                let element = self.mask & (read_buffer >> offset);
×
915

916
                // We apply the function to the element.
917
                let new_element = f(element);
×
918

919
                // We set the element in the new word.
920
                write_buffer |= new_element << offset;
×
921
            }
922

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

926
            let mut new_write_buffer = B::Word::ZERO;
×
927
            if upper_word_limit != global_bit_index {
×
928
                let remainder = upper_word_limit - global_bit_index;
×
929
                let offset = global_bit_index - lower_word_limit;
×
930
                // We compose the element from the remaining elements in the
931
                // current word and the elements in the next word.
932
                let element = ((read_buffer >> offset) | (next_word << remainder)) & self.mask;
×
933
                global_bit_index += bit_width;
×
934

935
                // We apply the function to the element.
936
                let new_element = f(element);
×
937

938
                write_buffer |= new_element << offset;
×
939

940
                new_write_buffer = new_element >> remainder;
×
941
            };
942

943
            read_buffer = next_word;
×
944

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

947
            write_buffer = new_write_buffer;
×
948
            lower_word_limit = upper_word_limit;
×
949
            upper_word_limit += bits;
×
950
        }
951

952
        let mut offset = global_bit_index - lower_word_limit;
×
953

954
        // We iterate across the elements in the word.
955
        while offset < self.len() * bit_width - global_bit_index {
×
956
            // We retrieve the value from the current word.
957
            let element = self.mask & (read_buffer >> offset);
×
958

959
            // We apply the function to the element.
960
            let new_element = f(element);
×
961

962
            // We set the element in the new word.
963
            write_buffer |= new_element << offset;
×
964
            offset += bit_width;
×
965
        }
966

967
        *unsafe { self.bits.as_mut().get_unchecked_mut(last_word_idx) } = write_buffer;
×
968
    }
969

970
    type ChunksMut<'a>
971
        = ChunksMut<'a, B::Word>
972
    where
973
        Self: 'a;
974

975
    type ChunksMutError = ChunksMutError<B::Word>;
976

977
    /// # Errors
978
    ///
979
    /// This method will return an error if the chunk size multiplied by
980
    /// the [bit width](BitWidth::bit_width) is not a multiple of
981
    /// `W::BITS` and more than one chunk must be returned.
982
    fn try_chunks_mut(
101✔
983
        &mut self,
984
        chunk_size: usize,
985
    ) -> Result<Self::ChunksMut<'_>, ChunksMutError<B::Word>> {
986
        let len = self.len();
303✔
987
        let bit_width = self.bit_width();
303✔
988
        let bits = B::Word::BITS as usize;
202✔
989
        if len <= chunk_size || (chunk_size * bit_width) % bits == 0 {
106✔
990
            // chunks_mut panics with chunk_size 0, so use 1 when the
991
            // product is zero (bit_width == 0); the iterator will yield
992
            // empty slices anyway.
993
            let words_per_chunk = Ord::max(1, (chunk_size * bit_width).div_ceil(bits));
495✔
994
            Ok(ChunksMut {
99✔
995
                remaining: len,
198✔
996
                bit_width: self.bit_width,
198✔
997
                chunk_size,
198✔
998
                iter: self.bits.as_mut()[..(len * bit_width).div_ceil(bits)]
396✔
999
                    .chunks_mut(words_per_chunk),
99✔
1000
            })
1001
        } else {
1002
            Err(ChunksMutError {
2✔
1003
                bit_width,
4✔
1004
                chunk_size,
2✔
1005
                _marker: core::marker::PhantomData,
2✔
1006
            })
1007
        }
1008
    }
1009
}
1010

1011
// Support for unchecked iterators
1012

1013
/// An [`UncheckedIterator`] over the values of a [`BitFieldVec`].
1014
#[derive(Debug, Clone, MemDbg, MemSize)]
1015
pub struct BitFieldVecUncheckedIter<'a, B: Backend<Word: Word>> {
1016
    vec: &'a BitFieldVec<B>,
1017
    word_index: usize,
1018
    window: B::Word,
1019
    fill: usize,
1020
}
1021

1022
impl<'a, B: Backend<Word: Word> + AsRef<[B::Word]>> BitFieldVecUncheckedIter<'a, B> {
1023
    fn new(vec: &'a BitFieldVec<B>, index: usize) -> Self {
695,732✔
1024
        if index > vec.len() {
1,391,464✔
1025
            panic!("Start index out of bounds: {} > {}", index, vec.len());
×
1026
        }
1027
        let bits = B::Word::BITS as usize;
1,391,464✔
1028
        let (fill, word_index);
×
1029
        let window = if index == vec.len() {
2,087,196✔
1030
            word_index = 0;
343✔
1031
            fill = 0;
343✔
1032
            B::Word::ZERO
343✔
1033
        } else {
1034
            let bit_offset = index * vec.bit_width;
1,390,778✔
1035
            let bit_index = bit_offset % bits;
1,390,778✔
1036

1037
            word_index = bit_offset / bits;
695,389✔
1038
            fill = bits - bit_index;
695,389✔
1039
            unsafe {
1040
                // SAFETY: index has been checked at the start and it is within bounds
1041
                *vec.bits.as_ref().get_unchecked(word_index) >> bit_index
1,390,778✔
1042
            }
1043
        };
1044
        Self {
1045
            vec,
1046
            word_index,
1047
            window,
1048
            fill,
1049
        }
1050
    }
1051
}
1052

1053
impl<B: Backend<Word: Word> + AsRef<[B::Word]>> crate::traits::UncheckedIterator
1054
    for BitFieldVecUncheckedIter<'_, B>
1055
{
1056
    type Item = B::Word;
1057
    unsafe fn next_unchecked(&mut self) -> B::Word {
35,202,101✔
1058
        let bit_width = self.vec.bit_width;
70,404,202✔
1059

1060
        if self.fill >= bit_width {
35,202,101✔
1061
            self.fill -= bit_width;
19,713,591✔
1062
            let res = self.window & self.vec.mask;
39,427,182✔
1063
            self.window >>= bit_width;
19,713,591✔
1064
            return res;
19,713,591✔
1065
        }
1066

1067
        let res = self.window;
30,977,020✔
1068
        self.word_index += 1;
15,488,510✔
1069
        self.window = *unsafe { self.vec.bits.as_ref().get_unchecked(self.word_index) };
30,977,020✔
1070
        let res = (res | (self.window << self.fill)) & self.vec.mask;
46,465,530✔
1071
        let used = bit_width - self.fill;
30,977,020✔
1072
        self.window >>= used;
15,488,510✔
1073
        self.fill = B::Word::BITS as usize - used; // not in a loop
15,488,510✔
1074
        res
15,488,510✔
1075
    }
1076
}
1077

1078
impl<'a, B: Backend<Word: Word> + AsRef<[B::Word]>> IntoUncheckedIterator for &'a BitFieldVec<B> {
1079
    type Item = B::Word;
1080
    type IntoUncheckedIter = BitFieldVecUncheckedIter<'a, B>;
1081
    fn into_unchecked_iter_from(self, from: usize) -> Self::IntoUncheckedIter {
382,453✔
1082
        BitFieldVecUncheckedIter::new(self, from)
1,147,359✔
1083
    }
1084
}
1085

1086
/// An [`UncheckedIterator`] moving backwards over the values of a [`BitFieldVec`].
1087
#[derive(Debug, Clone, MemDbg, MemSize)]
1088
pub struct BitFieldVecUncheckedBackIter<'a, B: Backend<Word: Word>> {
1089
    vec: &'a BitFieldVec<B>,
1090
    word_index: usize,
1091
    window: B::Word,
1092
    fill: usize,
1093
}
1094

1095
impl<'a, B: Backend<Word: Word> + AsRef<[B::Word]>> BitFieldVecUncheckedBackIter<'a, B> {
1096
    fn new(vec: &'a BitFieldVec<B>, index: usize) -> Self {
351,150✔
1097
        if index > vec.len() {
702,300✔
1098
            panic!("Start index out of bounds: {} > {}", index, vec.len());
×
1099
        }
1100
        let bits = B::Word::BITS as usize;
702,300✔
1101
        let (word_index, fill);
×
1102

1103
        let window = if index == 0 {
702,300✔
1104
            word_index = 0;
3,144✔
1105
            fill = 0;
3,144✔
1106
            B::Word::ZERO
3,144✔
1107
        } else {
1108
            // We have to handle the case of zero bit width
1109
            let bit_offset = (index * vec.bit_width).saturating_sub(1);
1,044,018✔
1110
            let bit_index = bit_offset % bits;
696,012✔
1111

1112
            word_index = bit_offset / bits;
348,006✔
1113
            fill = bit_index + 1;
348,006✔
1114
            unsafe {
1115
                // SAFETY: index has been checked at the start and it is within bounds
1116
                *vec.bits.as_ref().get_unchecked(word_index) << (bits - fill)
1,044,018✔
1117
            }
1118
        };
1119
        Self {
1120
            vec,
1121
            word_index,
1122
            window,
1123
            fill,
1124
        }
1125
    }
1126
}
1127

1128
impl<B: Backend<Word: Word> + AsRef<[B::Word]>> crate::traits::UncheckedIterator
1129
    for BitFieldVecUncheckedBackIter<'_, B>
1130
{
1131
    type Item = B::Word;
1132
    unsafe fn next_unchecked(&mut self) -> B::Word {
18,004,602✔
1133
        let bit_width = self.vec.bit_width;
36,009,204✔
1134

1135
        if self.fill >= bit_width {
18,004,602✔
1136
            self.fill -= bit_width;
10,580,460✔
1137
            self.window = self.window.rotate_left(bit_width as u32);
21,160,920✔
1138
            return self.window & self.vec.mask;
10,580,460✔
1139
        }
1140

1141
        let mut res = self.window.rotate_left(self.fill as u32);
29,696,568✔
1142
        self.word_index -= 1;
7,424,142✔
1143
        self.window = *unsafe { self.vec.bits.as_ref().get_unchecked(self.word_index) };
14,848,284✔
1144
        let used = bit_width - self.fill;
14,848,284✔
1145
        res = ((res << used) | (self.window >> (B::Word::BITS as usize - used))) & self.vec.mask; // not in a loop
22,272,426✔
1146
        self.window <<= used;
7,424,142✔
1147
        self.fill = B::Word::BITS as usize - used;
7,424,142✔
1148
        res
7,424,142✔
1149
    }
1150
}
1151

1152
impl<'a, B: Backend<Word: Word> + AsRef<[B::Word]>> IntoUncheckedBackIterator
1153
    for &'a BitFieldVec<B>
1154
{
1155
    type Item = B::Word;
1156
    type IntoUncheckedIterBack = BitFieldVecUncheckedBackIter<'a, B>;
1157

1158
    fn into_unchecked_iter_back(self) -> Self::IntoUncheckedIterBack {
×
1159
        BitFieldVecUncheckedBackIter::new(self, self.len())
×
1160
    }
1161

1162
    fn into_unchecked_iter_back_from(self, from: usize) -> Self::IntoUncheckedIterBack {
351,150✔
1163
        BitFieldVecUncheckedBackIter::new(self, from)
1,053,450✔
1164
    }
1165
}
1166

1167
/// An [`Iterator`] over the values of a [`BitFieldVec`].
1168
#[derive(Debug, Clone, MemDbg, MemSize)]
1169
pub struct BitFieldVecIter<'a, B: Backend<Word: Word>> {
1170
    unchecked: BitFieldVecUncheckedIter<'a, B>,
1171
    range: core::ops::Range<usize>,
1172
}
1173

1174
impl<'a, B: Backend<Word: Word> + AsRef<[B::Word]>> BitFieldVecIter<'a, B> {
1175
    fn new(vec: &'a BitFieldVec<B>, from: usize) -> Self {
313,279✔
1176
        let len = vec.len();
939,837✔
1177
        if from > len {
313,279✔
1178
            panic!("Start index out of bounds: {} > {}", from, len);
×
1179
        }
1180
        Self {
1181
            unchecked: BitFieldVecUncheckedIter::new(vec, from),
1,253,116✔
1182
            range: from..len,
313,279✔
1183
        }
1184
    }
1185
}
1186

1187
impl<B: Backend<Word: Word> + AsRef<[B::Word]>> Iterator for BitFieldVecIter<'_, B> {
1188
    type Item = B::Word;
1189
    fn next(&mut self) -> Option<Self::Item> {
16,189,268✔
1190
        if self.range.is_empty() {
32,378,536✔
1191
            return None;
313,206✔
1192
        }
1193
        // SAFETY: index has just been checked
1194
        let res = unsafe { self.unchecked.next_unchecked() };
47,628,186✔
1195
        self.range.start += 1;
15,876,062✔
1196
        Some(res)
15,876,062✔
1197
    }
1198

1199
    #[inline(always)]
1200
    fn size_hint(&self) -> (usize, Option<usize>) {
65✔
1201
        (self.range.len(), Some(self.range.len()))
195✔
1202
    }
1203
}
1204

1205
impl<B: Backend<Word: Word> + AsRef<[B::Word]>> ExactSizeIterator for BitFieldVecIter<'_, B> {
1206
    #[inline(always)]
1207
    fn len(&self) -> usize {
×
1208
        self.range.len()
×
1209
    }
1210
}
1211

1212
impl<B: Backend<Word: Word> + AsRef<[B::Word]>> FusedIterator for BitFieldVecIter<'_, B> {}
1213

1214
/// This implements iteration from the end, but it's slower than the forward iteration
1215
/// as here we do a random access, while in the forward iterator we do a sequential access
1216
/// and we keep a buffer of `W::BITS` bits to speed up the iteration.
1217
///
1218
/// If needed we could also keep a buffer from the end, but the logic would be more complex
1219
/// and potentially slower.
1220
impl<B: Backend<Word: Word> + AsRef<[B::Word]>> DoubleEndedIterator for BitFieldVecIter<'_, B> {
1221
    fn next_back(&mut self) -> Option<Self::Item> {
725✔
1222
        if self.range.is_empty() {
1,450✔
1223
            return None;
69✔
1224
        }
1225
        self.range.end -= 1;
656✔
1226
        // SAFETY: range.end was > range.start, so it is a valid index
1227
        let res = unsafe { self.unchecked.vec.get_value_unchecked(self.range.end) };
2,624✔
1228
        Some(res)
656✔
1229
    }
1230
}
1231

1232
/// Equality between bit-field vectors requires that the word is the same, the
1233
/// bit width is the same, and the content is the same.
1234
impl<B: Backend<Word: Word> + AsRef<[B::Word]>, C: Backend<Word = B::Word> + AsRef<[B::Word]>>
1235
    PartialEq<BitFieldVec<C>> for BitFieldVec<B>
1236
{
1237
    fn eq(&self, other: &BitFieldVec<C>) -> bool {
3,771✔
1238
        if self.bit_width() != other.bit_width() {
11,313✔
1239
            return false;
×
1240
        }
1241
        if self.len() != other.len() {
11,313✔
1242
            return false;
2✔
1243
        }
1244
        let bits = B::Word::BITS as usize;
7,538✔
1245
        let bit_len = self.len() * self.bit_width();
15,076✔
1246
        if self.bits.as_ref()[..bit_len / bits] != other.bits.as_ref()[..bit_len / bits] {
15,076✔
1247
            return false;
×
1248
        }
1249

1250
        let residual = bit_len % bits;
7,538✔
1251
        residual == 0
3,769✔
1252
            || (self.bits.as_ref()[bit_len / bits] ^ other.bits.as_ref()[bit_len / bits])
24,682✔
1253
                << (bits - residual)
3,526✔
1254
                == B::Word::ZERO
3,526✔
1255
    }
1256
}
1257

1258
impl<'a, B: Backend<Word: Word> + AsRef<[B::Word]>> IntoIterator for &'a BitFieldVec<B> {
1259
    type Item = B::Word;
1260
    type IntoIter = BitFieldVecIter<'a, B>;
1261

1262
    fn into_iter(self) -> Self::IntoIter {
71✔
1263
        BitFieldVecIter::new(self, 0)
142✔
1264
    }
1265
}
1266

1267
impl<'a, B: Backend<Word: Word> + AsRef<[B::Word]>> IntoIteratorFrom for &'a BitFieldVec<B> {
1268
    type IntoIterFrom = BitFieldVecIter<'a, B>;
1269

1270
    fn into_iter_from(self, from: usize) -> Self::IntoIterFrom {
×
1271
        BitFieldVecIter::new(self, from)
×
1272
    }
1273
}
1274

1275
impl<W: Word> core::iter::Extend<W> for BitFieldVec<Vec<W>> {
1276
    fn extend<T: IntoIterator<Item = W>>(&mut self, iter: T) {
1✔
1277
        for value in iter {
17✔
1278
            self.push(value);
16✔
1279
        }
1280
    }
1281
}
1282

1283
impl<B: Backend<Word: Word> + AsRef<[B::Word]>> BitFieldVec<B> {
1284
    pub fn iter_from(&self, from: usize) -> BitFieldVecIter<'_, B> {
313,208✔
1285
        BitFieldVecIter::new(self, from)
939,624✔
1286
    }
1287

1288
    pub fn iter(&self) -> BitFieldVecIter<'_, B> {
1,202✔
1289
        self.iter_from(0)
2,404✔
1290
    }
1291
}
1292
/// A tentatively thread-safe vector of bit fields of fixed width (AKA "compact arrays",
1293
/// "bit array", etc.)
1294
///
1295
/// This implementation provides some concurrency guarantees, albeit not
1296
/// full-fledged thread safety: more precisely, we can guarantee thread-safety
1297
/// if the bit width is a power of two; otherwise, concurrent writes to values
1298
/// that cross word boundaries might end up in different threads succeeding in
1299
/// writing only part of a value. If the user can guarantee that no two threads
1300
/// ever write to the same boundary-crossing value, then no race condition can
1301
/// happen.
1302
///
1303
/// See the [module documentation](crate::bits) for more details.
1304
#[derive(Debug, Clone, Hash, MemDbg, MemSize, Delegate)]
1305
#[cfg_attr(feature = "epserde", derive(epserde::Epserde))]
1306
#[cfg_attr(
1307
    feature = "epserde",
1308
    epserde(bound(
1309
        deser = "for<'a> <B as epserde::deser::DeserInner>::DeserType<'a>: Backend<Word = B::Word>"
1310
    ))
1311
)]
1312
#[delegate(crate::traits::Backend, target = "bits")]
1313
pub struct AtomicBitFieldVec<
1314
    B: Backend<Word: PrimitiveAtomicUnsigned<Value: Word>> = Vec<Atomic<usize>>,
1315
> {
1316
    /// The underlying storage.
1317
    bits: B,
1318
    /// The bit width of the values stored in the vector.
1319
    bit_width: usize,
1320
    /// A mask with its lowest `bit_width` bits set to one.
1321
    mask: <B::Word as PrimitiveAtomic>::Value,
1322
    /// The length of the vector.
1323
    len: usize,
1324
}
1325

1326
impl<B: Backend<Word: PrimitiveAtomicUnsigned<Value: Word>>> AtomicBitFieldVec<B> {
1327
    /// # Safety
1328
    /// `len` * `bit_width` must be between 0 (included) and the number of
1329
    /// bits in `bits` (included).
1330
    #[inline(always)]
1331
    pub unsafe fn from_raw_parts(bits: B, bit_width: usize, len: usize) -> Self {
184✔
1332
        Self {
1333
            bits,
1334
            bit_width,
1335
            mask: mask(bit_width),
368✔
1336
            len,
1337
        }
1338
    }
1339

1340
    /// Returns the backend, the bit width, and the length, consuming this
1341
    /// vector.
1342
    #[inline(always)]
1343
    pub fn into_raw_parts(self) -> (B, usize, usize) {
184✔
1344
        (self.bits, self.bit_width, self.len)
368✔
1345
    }
1346

1347
    /// Returns the mask used to extract values from the vector.
1348
    /// This will keep the lowest `bit_width` bits.
1349
    pub const fn mask(&self) -> <B::Word as PrimitiveAtomic>::Value {
184✔
1350
        self.mask
184✔
1351
    }
1352
}
1353

1354
impl<B: Backend<Word: PrimitiveAtomicUnsigned<Value: Word>> + AsRef<[B::Word]>>
1355
    AtomicBitFieldVec<B>
1356
{
1357
    /// Returns the backend of the `AtomicBitFieldVec` as a slice of atomic words.
1358
    pub fn as_slice(&self) -> &[B::Word] {
4✔
1359
        self.bits.as_ref()
4✔
1360
    }
1361
}
1362

1363
impl<A: PrimitiveAtomicUnsigned<Value: Word>> AtomicBitFieldVec<Vec<A>> {
1364
    pub fn new(bit_width: usize, len: usize) -> AtomicBitFieldVec<Vec<A>> {
195✔
1365
        // we need at least two words to avoid branches in the gets
1366
        let n_of_words = Ord::max(1, (len * bit_width).div_ceil(A::Value::BITS as usize));
975✔
1367
        AtomicBitFieldVec {
1368
            bits: (0..n_of_words).map(|_| A::new(A::Value::ZERO)).collect(),
9,648✔
1369
            bit_width,
1370
            mask: mask(bit_width),
390✔
1371
            len,
1372
        }
1373
    }
1374
}
1375

1376
impl<B: Backend<Word: PrimitiveAtomicUnsigned<Value: Word>>> AtomicBitWidth
1377
    for AtomicBitFieldVec<B>
1378
{
1379
    #[inline(always)]
1380
    fn atomic_bit_width(&self) -> usize {
184✔
1381
        debug_assert!(self.bit_width <= <B::Word as PrimitiveAtomic>::Value::BITS as usize);
368✔
1382
        self.bit_width
184✔
1383
    }
1384
}
1385

1386
impl<B: Backend<Word: PrimitiveAtomicUnsigned<Value: Word>> + AsRef<[B::Word]>> SliceByValue
1387
    for AtomicBitFieldVec<B>
1388
{
1389
    type Value = <B::Word as PrimitiveAtomic>::Value;
1390

1391
    #[inline(always)]
1392
    fn len(&self) -> usize {
×
1393
        self.len
×
1394
    }
1395

1396
    unsafe fn get_value_unchecked(&self, index: usize) -> Self::Value {
×
1397
        unsafe { self.get_atomic_unchecked(index, Ordering::Relaxed) }
×
1398
    }
1399
}
1400

1401
impl<B: Backend<Word: PrimitiveAtomicUnsigned<Value: Word>> + AsRef<[B::Word]>>
1402
    AtomicBitFieldSlice<B::Word> for AtomicBitFieldVec<B>
1403
{
1404
    #[inline]
1405
    fn len(&self) -> usize {
404,824✔
1406
        self.len
404,824✔
1407
    }
1408

1409
    #[inline]
1410
    unsafe fn get_atomic_unchecked(
404,825✔
1411
        &self,
1412
        index: usize,
1413
        order: Ordering,
1414
    ) -> <B::Word as PrimitiveAtomic>::Value {
1415
        let wbits = <B::Word as PrimitiveAtomic>::Value::BITS as usize;
809,650✔
1416
        let pos = index * self.bit_width;
809,650✔
1417
        let word_index = pos / wbits;
809,650✔
1418
        let bit_index = pos % wbits;
809,650✔
1419
        let data = self.bits.as_ref();
1,214,475✔
1420

1421
        unsafe {
1422
            if bit_index + self.bit_width <= wbits {
404,825✔
1423
                (data.get_unchecked(word_index).load(order) >> bit_index) & self.mask
939,176✔
1424
            } else {
1425
                ((data.get_unchecked(word_index).load(order) >> bit_index)
850,155✔
1426
                    | (data.get_unchecked(word_index + 1).load(order) << (wbits - bit_index)))
850,155✔
1427
                    & self.mask
170,031✔
1428
            }
1429
        }
1430
    }
1431

1432
    // We reimplement set as we have the mask in the structure.
1433

1434
    /// Sets the element of the slice at the specified index.
1435
    ///
1436
    /// May panic if the index is not in [0..[len](SliceByValue::len))
1437
    /// or the value does not fit in [`BitWidth::bit_width`] bits.
1438
    #[inline(always)]
1439
    fn set_atomic(
56,026✔
1440
        &self,
1441
        index: usize,
1442
        value: <B::Word as PrimitiveAtomic>::Value,
1443
        order: Ordering,
1444
    ) {
1445
        panic_if_out_of_bounds!(index, self.len);
168,078✔
1446
        panic_if_value!(value, self.mask, self.bit_width);
168,075✔
1447
        unsafe {
1448
            self.set_atomic_unchecked(index, value, order);
224,096✔
1449
        }
1450
    }
1451

1452
    #[inline]
1453
    unsafe fn set_atomic_unchecked(
186,235✔
1454
        &self,
1455
        index: usize,
1456
        value: <B::Word as PrimitiveAtomic>::Value,
1457
        order: Ordering,
1458
    ) {
1459
        unsafe {
1460
            let wbits = <B::Word as PrimitiveAtomic>::Value::BITS as usize;
372,470✔
1461
            debug_assert!(self.bit_width <= wbits);
372,470✔
1462
            let pos = index * self.bit_width;
372,470✔
1463
            let word_index = pos / wbits;
372,470✔
1464
            let bit_index = pos % wbits;
372,470✔
1465
            let data = self.bits.as_ref();
558,705✔
1466

1467
            if bit_index + self.bit_width <= wbits {
186,235✔
1468
                // this is consistent
1469
                let mut current = data.get_unchecked(word_index).load(order);
544,690✔
1470
                loop {
×
1471
                    let mut new = current;
217,876✔
1472
                    new &= !(self.mask << bit_index);
217,876✔
1473
                    new |= value << bit_index;
217,876✔
1474

1475
                    match data
326,814✔
1476
                        .get_unchecked(word_index)
217,876✔
1477
                        .compare_exchange(current, new, order, order)
435,752✔
1478
                    {
1479
                        Ok(_) => break,
108,938✔
1480
                        Err(e) => current = e,
×
1481
                    }
1482
                }
1483
            } else {
1484
                let mut word = data.get_unchecked(word_index).load(order);
386,485✔
1485
                // try to wait for the other thread to finish
1486
                fence(Ordering::Acquire);
154,594✔
1487
                loop {
×
1488
                    let mut new = word;
154,594✔
1489
                    new &= (<B::Word as PrimitiveAtomic>::Value::ONE << bit_index)
77,297✔
1490
                        - <B::Word as PrimitiveAtomic>::Value::ONE;
77,297✔
1491
                    new |= value << bit_index;
154,594✔
1492

1493
                    match data
231,891✔
1494
                        .get_unchecked(word_index)
154,594✔
1495
                        .compare_exchange(word, new, order, order)
309,188✔
1496
                    {
1497
                        Ok(_) => break,
77,297✔
1498
                        Err(e) => word = e,
×
1499
                    }
1500
                }
1501
                fence(Ordering::Release);
154,594✔
1502

1503
                // ensures that the compiler does not reorder the two atomic operations
1504
                // this should increase the probability of having consistency
1505
                // between two concurrent writes as they will both execute the set
1506
                // of the bits in the same order, and the release / acquire fence
1507
                // should try to synchronize the threads as much as possible
1508
                compiler_fence(Ordering::SeqCst);
154,594✔
1509

1510
                let mut word = data.get_unchecked(word_index + 1).load(order);
386,485✔
1511
                fence(Ordering::Acquire);
154,594✔
1512
                loop {
×
1513
                    let mut new = word;
154,594✔
1514
                    new &= !(self.mask >> (wbits - bit_index));
231,891✔
1515
                    new |= value >> (wbits - bit_index);
231,891✔
1516

1517
                    match data
231,891✔
1518
                        .get_unchecked(word_index + 1)
154,594✔
1519
                        .compare_exchange(word, new, order, order)
309,188✔
1520
                    {
1521
                        Ok(_) => break,
77,297✔
1522
                        Err(e) => word = e,
×
1523
                    }
1524
                }
1525
                fence(Ordering::Release);
154,594✔
1526
            }
1527
        }
1528
    }
1529

1530
    fn reset_atomic(&mut self, ordering: Ordering) {
1✔
1531
        let bit_len = self.len * self.bit_width;
2✔
1532
        let full_words = bit_len / <B::Word as PrimitiveAtomic>::Value::BITS as usize;
2✔
1533
        let residual = bit_len % <B::Word as PrimitiveAtomic>::Value::BITS as usize;
2✔
1534
        let bits = self.bits.as_ref();
3✔
1535
        bits[..full_words]
1✔
1536
            .iter()
1537
            .for_each(|x| x.store(<B::Word as PrimitiveAtomic>::Value::ZERO, ordering));
22✔
1538
        if residual != 0 {
2✔
1539
            bits[full_words].fetch_and(
3✔
1540
                <B::Word as PrimitiveAtomic>::Value::MAX << residual,
1✔
1541
                ordering,
1✔
1542
            );
1543
        }
1544
    }
1545

1546
    #[cfg(feature = "rayon")]
1547
    fn par_reset_atomic(&mut self, ordering: Ordering) {
1✔
1548
        let bit_len = self.len * self.bit_width;
2✔
1549
        let full_words = bit_len / <B::Word as PrimitiveAtomic>::Value::BITS as usize;
2✔
1550
        let residual = bit_len % <B::Word as PrimitiveAtomic>::Value::BITS as usize;
2✔
1551
        let bits = self.bits.as_ref();
3✔
1552
        bits[..full_words]
1✔
1553
            .par_iter()
1554
            .with_min_len(crate::RAYON_MIN_LEN)
1✔
1555
            .for_each(|x| x.store(<B::Word as PrimitiveAtomic>::Value::ZERO, ordering));
22✔
1556
        if residual != 0 {
2✔
1557
            bits[full_words].fetch_and(
3✔
1558
                <B::Word as PrimitiveAtomic>::Value::MAX << residual,
1✔
1559
                ordering,
1✔
1560
            );
1561
        }
1562
    }
1563
}
1564

1565
// Conversions
1566

1567
impl<W: Word + AtomicPrimitive<Atomic: PrimitiveAtomicUnsigned>>
1568
    From<AtomicBitFieldVec<Vec<W::Atomic>>> for BitFieldVec<Vec<W>>
1569
{
1570
    #[inline]
1571
    fn from(value: AtomicBitFieldVec<Vec<W::Atomic>>) -> Self {
190✔
1572
        BitFieldVec {
1573
            bits: transmute_vec_from_atomic(value.bits),
570✔
1574
            len: value.len,
380✔
1575
            bit_width: value.bit_width,
190✔
1576
            mask: value.mask,
190✔
1577
        }
1578
    }
1579
}
1580

1581
impl<W: Word + AtomicPrimitive<Atomic: PrimitiveAtomicUnsigned>>
1582
    From<AtomicBitFieldVec<Box<[W::Atomic]>>> for BitFieldVec<Box<[W]>>
1583
{
1584
    #[inline]
1585
    fn from(value: AtomicBitFieldVec<Box<[W::Atomic]>>) -> Self {
1✔
1586
        BitFieldVec {
1587
            bits: transmute_boxed_slice_from_atomic(value.bits),
3✔
1588

1589
            len: value.len,
2✔
1590
            bit_width: value.bit_width,
1✔
1591
            mask: value.mask,
1✔
1592
        }
1593
    }
1594
}
1595

1596
impl<'a, W: Word + AtomicPrimitive<Atomic: PrimitiveAtomicUnsigned>>
1597
    From<AtomicBitFieldVec<&'a [W::Atomic]>> for BitFieldVec<&'a [W]>
1598
{
1599
    #[inline]
1600
    fn from(value: AtomicBitFieldVec<&'a [W::Atomic]>) -> Self {
1✔
1601
        BitFieldVec {
1602
            bits: unsafe { core::mem::transmute::<&'a [W::Atomic], &'a [W]>(value.bits) },
3✔
1603
            len: value.len,
2✔
1604
            bit_width: value.bit_width,
1✔
1605
            mask: value.mask,
1✔
1606
        }
1607
    }
1608
}
1609

1610
impl<'a, W: Word + AtomicPrimitive<Atomic: PrimitiveAtomicUnsigned>>
1611
    From<AtomicBitFieldVec<&'a mut [W::Atomic]>> for BitFieldVec<&'a mut [W]>
1612
{
1613
    #[inline]
1614
    fn from(value: AtomicBitFieldVec<&'a mut [W::Atomic]>) -> Self {
1✔
1615
        BitFieldVec {
1616
            bits: unsafe { core::mem::transmute::<&'a mut [W::Atomic], &'a mut [W]>(value.bits) },
2✔
1617
            len: value.len,
2✔
1618
            bit_width: value.bit_width,
1✔
1619
            mask: value.mask,
1✔
1620
        }
1621
    }
1622
}
1623

1624
impl<W: Word + AtomicPrimitive<Atomic: PrimitiveAtomicUnsigned>> From<BitFieldVec<Vec<W>>>
1625
    for AtomicBitFieldVec<Vec<W::Atomic>>
1626
{
1627
    #[inline]
1628
    fn from(value: BitFieldVec<Vec<W>>) -> Self {
369✔
1629
        AtomicBitFieldVec {
1630
            bits: transmute_vec_into_atomic(value.bits),
1,107✔
1631

1632
            len: value.len,
738✔
1633
            bit_width: value.bit_width,
369✔
1634
            mask: value.mask,
369✔
1635
        }
1636
    }
1637
}
1638

1639
impl<W: Word + AtomicPrimitive<Atomic: PrimitiveAtomicUnsigned>> From<BitFieldVec<Box<[W]>>>
1640
    for AtomicBitFieldVec<Box<[W::Atomic]>>
1641
{
1642
    #[inline]
1643
    fn from(value: BitFieldVec<Box<[W]>>) -> Self {
1✔
1644
        AtomicBitFieldVec {
1645
            bits: transmute_boxed_slice_into_atomic(value.bits),
3✔
1646
            len: value.len,
2✔
1647
            bit_width: value.bit_width,
1✔
1648
            mask: value.mask,
1✔
1649
        }
1650
    }
1651
}
1652

1653
impl<'a, W: Word + AtomicPrimitive<Atomic: PrimitiveAtomicUnsigned>> TryFrom<BitFieldVec<&'a [W]>>
1654
    for AtomicBitFieldVec<&'a [W::Atomic]>
1655
{
1656
    type Error = CannotCastToAtomicError<W>;
1657

1658
    #[inline]
1659
    fn try_from(value: BitFieldVec<&'a [W]>) -> Result<Self, Self::Error> {
1✔
1660
        if core::mem::align_of::<W::Atomic>() != core::mem::align_of::<W>() {
1✔
1661
            return Err(CannotCastToAtomicError::default());
×
1662
        }
1663
        Ok(AtomicBitFieldVec {
1✔
1664
            bits: unsafe { core::mem::transmute::<&'a [W], &'a [W::Atomic]>(value.bits) },
3✔
1665
            len: value.len,
2✔
1666
            bit_width: value.bit_width,
1✔
1667
            mask: value.mask,
1✔
1668
        })
1669
    }
1670
}
1671

1672
impl<'a, W: Word + AtomicPrimitive<Atomic: PrimitiveAtomicUnsigned>>
1673
    TryFrom<BitFieldVec<&'a mut [W]>> for AtomicBitFieldVec<&'a mut [W::Atomic]>
1674
{
1675
    type Error = CannotCastToAtomicError<W>;
1676

1677
    #[inline]
1678
    fn try_from(value: BitFieldVec<&'a mut [W]>) -> Result<Self, Self::Error> {
1✔
1679
        if core::mem::align_of::<W::Atomic>() != core::mem::align_of::<W>() {
1✔
1680
            return Err(CannotCastToAtomicError::default());
×
1681
        }
1682
        Ok(AtomicBitFieldVec {
1✔
1683
            bits: unsafe { core::mem::transmute::<&'a mut [W], &'a mut [W::Atomic]>(value.bits) },
2✔
1684
            len: value.len,
2✔
1685
            bit_width: value.bit_width,
1✔
1686
            mask: value.mask,
1✔
1687
        })
1688
    }
1689
}
1690

1691
impl<W: Word> From<BitFieldVec<Vec<W>>> for BitFieldVec<Box<[W]>> {
1692
    fn from(value: BitFieldVec<Vec<W>>) -> Self {
308✔
1693
        BitFieldVec {
1694
            bits: value.bits.into_boxed_slice(),
924✔
1695
            len: value.len,
616✔
1696
            bit_width: value.bit_width,
308✔
1697
            mask: value.mask,
308✔
1698
        }
1699
    }
1700
}
1701

1702
impl<W: Word> From<BitFieldVec<Box<[W]>>> for BitFieldVec<Vec<W>> {
1703
    fn from(value: BitFieldVec<Box<[W]>>) -> Self {
1✔
1704
        BitFieldVec {
1705
            bits: value.bits.into_vec(),
3✔
1706
            len: value.len,
2✔
1707
            bit_width: value.bit_width,
1✔
1708
            mask: value.mask,
1✔
1709
        }
1710
    }
1711
}
1712

1713
impl<'a, B: Backend<Word: Word> + AsRef<[B::Word]>> value_traits::iter::IterateByValueGat<'a>
1714
    for BitFieldVec<B>
1715
{
1716
    type Item = B::Word;
1717
    type Iter = BitFieldVecIter<'a, B>;
1718
}
1719

1720
impl<B: Backend<Word: Word> + AsRef<[B::Word]>> value_traits::iter::IterateByValue
1721
    for BitFieldVec<B>
1722
{
1723
    fn iter_value(&self) -> <Self as value_traits::iter::IterateByValueGat<'_>>::Iter {
×
1724
        self.iter_from(0)
×
1725
    }
1726
}
1727

1728
impl<'a, B: Backend<Word: Word> + AsRef<[B::Word]>> value_traits::iter::IterateByValueFromGat<'a>
1729
    for BitFieldVec<B>
1730
{
1731
    type Item = B::Word;
1732
    type IterFrom = BitFieldVecIter<'a, B>;
1733
}
1734

1735
impl<B: Backend<Word: Word> + AsRef<[B::Word]>> value_traits::iter::IterateByValueFrom
1736
    for BitFieldVec<B>
1737
{
1738
    fn iter_value_from(
×
1739
        &self,
1740
        from: usize,
1741
    ) -> <Self as value_traits::iter::IterateByValueGat<'_>>::Iter {
1742
        self.iter_from(from)
×
1743
    }
1744
}
1745

1746
impl<'a, 'b, B: Backend<Word: Word> + AsRef<[B::Word]>> value_traits::iter::IterateByValueGat<'a>
1747
    for BitFieldVecSubsliceImpl<'b, B>
1748
{
1749
    type Item = B::Word;
1750
    type Iter = BitFieldVecIter<'a, B>;
1751
}
1752

1753
impl<'a, B: Backend<Word: Word> + AsRef<[B::Word]>> value_traits::iter::IterateByValue
1754
    for BitFieldVecSubsliceImpl<'a, B>
1755
{
1756
    fn iter_value(&self) -> <Self as value_traits::iter::IterateByValueGat<'_>>::Iter {
×
1757
        self.slice.iter_from(0)
×
1758
    }
1759
}
1760

1761
impl<'a, 'b, B: Backend<Word: Word> + AsRef<[B::Word]>>
1762
    value_traits::iter::IterateByValueFromGat<'a> for BitFieldVecSubsliceImpl<'b, B>
1763
{
1764
    type Item = B::Word;
1765
    type IterFrom = BitFieldVecIter<'a, B>;
1766
}
1767

1768
impl<'a, B: Backend<Word: Word> + AsRef<[B::Word]>> value_traits::iter::IterateByValueFrom
1769
    for BitFieldVecSubsliceImpl<'a, B>
1770
{
1771
    fn iter_value_from(
×
1772
        &self,
1773
        from: usize,
1774
    ) -> <Self as value_traits::iter::IterateByValueGat<'_>>::Iter {
1775
        self.slice.iter_from(from)
×
1776
    }
1777
}
1778

1779
impl<'a, 'b, B: Backend<Word: Word> + AsRef<[B::Word]>> value_traits::iter::IterateByValueGat<'a>
1780
    for BitFieldVecSubsliceImplMut<'b, B>
1781
{
1782
    type Item = B::Word;
1783
    type Iter = BitFieldVecIter<'a, B>;
1784
}
1785

1786
impl<'a, B: Backend<Word: Word> + AsRef<[B::Word]>> value_traits::iter::IterateByValue
1787
    for BitFieldVecSubsliceImplMut<'a, B>
1788
{
1789
    fn iter_value(&self) -> <Self as value_traits::iter::IterateByValueGat<'_>>::Iter {
×
1790
        self.slice.iter_from(0)
×
1791
    }
1792
}
1793

1794
impl<'a, 'b, B: Backend<Word: Word> + AsRef<[B::Word]>>
1795
    value_traits::iter::IterateByValueFromGat<'a> for BitFieldVecSubsliceImplMut<'b, B>
1796
{
1797
    type Item = B::Word;
1798
    type IterFrom = BitFieldVecIter<'a, B>;
1799
}
1800

1801
impl<'a, B: Backend<Word: Word> + AsRef<[B::Word]>> value_traits::iter::IterateByValueFrom
1802
    for BitFieldVecSubsliceImplMut<'a, B>
1803
{
1804
    fn iter_value_from(
×
1805
        &self,
1806
        from: usize,
1807
    ) -> <Self as value_traits::iter::IterateByValueGat<'_>>::Iter {
1808
        self.slice.iter_from(from)
×
1809
    }
1810
}
1811

1812
#[cfg(test)]
1813
mod tests {
1814
    use super::*;
1815

1816
    #[test]
1817
    fn test_with_capacity() {
1818
        let mut b = BitFieldVec::<Vec<usize>>::with_capacity(10, 100);
1819
        let capacity = b.bits.capacity();
1820
        for _ in 0..100 {
1821
            b.push(0);
1822
        }
1823
        assert_eq!(b.bits.capacity(), capacity);
1824
    }
1825

1826
    fn copy<
1827
        B: Backend<Word: Word> + AsRef<[B::Word]>,
1828
        C: Backend<Word = B::Word> + AsRef<[B::Word]> + AsMut<[B::Word]>,
1829
    >(
1830
        source: &BitFieldVec<B>,
1831
        from: usize,
1832
        dest: &mut BitFieldVec<C>,
1833
        to: usize,
1834
        len: usize,
1835
    ) {
1836
        let len = Ord::min(Ord::min(len, dest.len - to), source.len - from);
1837
        for i in 0..len {
1838
            dest.set_value(to + i, source.index_value(from + i));
1839
        }
1840
    }
1841

1842
    #[test]
1843
    fn test_copy() {
1844
        for src_pattern in 0..8 {
1845
            for dst_pattern in 0..8 {
1846
                // if from_first_word == from_last_word && to_first_word == to_last_word
1847
                let source = bit_field_vec![3 => src_pattern; 100];
1848
                let mut dest_actual = bit_field_vec![3 => dst_pattern; 100];
1849
                let mut dest_expected = dest_actual.clone();
1850
                source.copy(1, &mut dest_actual, 2, 10);
1851
                copy(&source, 1, &mut dest_expected, 2, 10);
1852
                assert_eq!(dest_actual, dest_expected);
1853
                // else if from_first_word == from_last_word
1854
                let source = bit_field_vec![3 => src_pattern; 100];
1855
                let mut dest_actual = bit_field_vec![3 => dst_pattern; 100];
1856
                let mut dest_expected = dest_actual.clone();
1857
                source.copy(1, &mut dest_actual, 20, 10);
1858
                copy(&source, 1, &mut dest_expected, 20, 10);
1859
                assert_eq!(dest_actual, dest_expected);
1860
                // else if to_first_word == to_last_word
1861
                let source = bit_field_vec![3 => src_pattern; 100];
1862
                let mut dest_actual = bit_field_vec![3 => dst_pattern; 100];
1863
                let mut dest_expected = dest_actual.clone();
1864
                source.copy(20, &mut dest_actual, 1, 10);
1865
                copy(&source, 20, &mut dest_expected, 1, 10);
1866
                assert_eq!(dest_actual, dest_expected);
1867
                // else if src_bit == dest_bit (residual = 1)
1868
                let source = bit_field_vec![3 => src_pattern; 1000];
1869
                let mut dest_actual = bit_field_vec![3 => dst_pattern; 1000];
1870
                let mut dest_expected = dest_actual.clone();
1871
                source.copy(3, &mut dest_actual, 3 + 3 * 128, 40);
1872
                copy(&source, 3, &mut dest_expected, 3 + 3 * 128, 40);
1873
                assert_eq!(dest_actual, dest_expected);
1874
                // else if src_bit == dest_bit (residual = 64)
1875
                let source = bit_field_vec![3 => src_pattern; 1000];
1876
                let mut dest_actual = bit_field_vec![3 => dst_pattern; 1000];
1877
                let mut dest_expected = dest_actual.clone();
1878
                source.copy(3, &mut dest_actual, 3 + 3 * 128, 61);
1879
                copy(&source, 3, &mut dest_expected, 3 + 3 * 128, 61);
1880
                assert_eq!(dest_actual, dest_expected);
1881
                // else if src_bit < dest_bit (residual = 1)
1882
                let source = bit_field_vec![3 => src_pattern; 1000];
1883
                let mut dest_actual = bit_field_vec![3 => dst_pattern; 1000];
1884
                let mut dest_expected = dest_actual.clone();
1885
                source.copy(3, &mut dest_actual, 7 + 64 * 3, 40);
1886
                copy(&source, 3, &mut dest_expected, 7 + 64 * 3, 40);
1887
                assert_eq!(dest_actual, dest_expected);
1888
                // else if src_bit < dest_bit (residual = 64)
1889
                let source = bit_field_vec![3 => src_pattern; 1000];
1890
                let mut dest_actual = bit_field_vec![3 => dst_pattern; 1000];
1891
                let mut dest_expected = dest_actual.clone();
1892
                source.copy(3, &mut dest_actual, 7 + 64 * 3, 40 + 17);
1893
                copy(&source, 3, &mut dest_expected, 7 + 64 * 3, 40 + 17);
1894
                assert_eq!(dest_actual, dest_expected);
1895
                // else if src_bit > dest_bit (residual = 1)
1896
                let source = bit_field_vec![3 => src_pattern; 1000];
1897
                let mut dest_actual = bit_field_vec![3 => dst_pattern; 1000];
1898
                let mut dest_expected = dest_actual.clone();
1899
                source.copy(7, &mut dest_actual, 3 + 64 * 3, 40 + 64);
1900
                copy(&source, 7, &mut dest_expected, 3 + 64 * 3, 40 + 64);
1901
                assert_eq!(dest_actual, dest_expected);
1902
                // else if src_bit > dest_bit (residual = 64)
1903
                let source = bit_field_vec![3 => src_pattern; 1000];
1904
                let mut dest_actual = bit_field_vec![3 => dst_pattern; 1000];
1905
                let mut dest_expected = dest_actual.clone();
1906
                source.copy(7, &mut dest_actual, 3 + 64 * 3, 40 + 21 + 64);
1907
                copy(&source, 7, &mut dest_expected, 3 + 64 * 3, 40 + 21 + 64);
1908
                assert_eq!(dest_actual, dest_expected);
1909
            }
1910
        }
1911
    }
1912
}
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