compressed-intvec 0.6.0

Space-efficient integer vectors with fixed-width, variable-length, and sequence-oriented encodings.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
//! # [`FixedVec`] Iterators
//!
//! This module provides iterators for sequential access to the elements of a
//! [`FixedVec`]. The iterators decode values on the fly without allocating an
//! intermediate buffer, making them efficient for processing large datasets.
//!
//! The core iterators ([`FixedVecIter`], [`FixedVecSliceIter`]) are stateful and
//! employ a bit-windowing technique. They decode values on the fly without
//! allocating an intermediate buffer. They support both forward and reverse
//! iteration.
//!
//! # Provided Iterators
//!
//! - [`FixedVecIter`]: A stateful, bidirectional iterator over the elements of a borrowed [`FixedVec`].
//! - [`FixedVecIntoIter`]: A consuming, bidirectional iterator that takes ownership of a [`FixedVec`].
//! - [`FixedVecSliceIter`]: A stateful, bidirectional iterator over the elements of a [`FixedVecSlice`].
//! - [`Chunks`]: An iterator that yields non-overlapping, immutable slices ([`FixedVecSlice`]).
//! - [`Windows`]: An iterator that yields overlapping, immutable slices ([`FixedVecSlice`]).
//! - [`FixedVecUncheckedIter`]: An `unsafe` bidirectional iterator that omits bounds checks for maximum performance.
//!
//! # Examples
//!
//! ## Iterating over elements
//!
//! ```rust
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! use compressed_intvec::fixed::{FixedVec, SFixedVec};
//!
//! let data: &[i16] = &[-100, 0, 100, 200];
//! let vec: SFixedVec<i16> = FixedVec::builder().build(data)?;
//!
//! let mut sum = 0;
//! for value in vec.iter() {
//!     sum += value;
//! }
//!
//! assert_eq!(sum, 200);
//! # Ok(())
//! # }
//! ```
//!
//! ## Bidirectional Iteration
//!
//! The main iterators implement [`DoubleEndedIterator`], allowing for
//! traversal from both ends of the sequence.
//!
//! ```rust
//! use compressed_intvec::fixed::{FixedVec, UFixedVec};
//!
//! let vec: UFixedVec<u8> = (0..=5u8).collect();
//! let mut iter = vec.iter();
//!
//! assert_eq!(iter.next(), Some(0));
//! assert_eq!(iter.next_back(), Some(5));
//! assert_eq!(iter.next(), Some(1));
//! assert_eq!(iter.next_back(), Some(4));
//!
//! // The iterator correctly tracks its remaining length.
//! assert_eq!(iter.len(), 2);
//!
//! assert_eq!(iter.next(), Some(2));
//! assert_eq!(iter.next(), Some(3));
//! assert_eq!(iter.next(), None);
//! ```
//!
//! ## Iterating over a Slice
//!
//! You can also create an iterator over a zero-copy slice of a vector.
//!
//! ```rust
//! use compressed_intvec::fixed::{FixedVec, UFixedVec};
//!
//! let vec: UFixedVec<u32> = (0..100u32).collect();
//!
//! // Create a slice containing elements from index 20 to 29.
//! let slice = vec.slice(20, 10).expect("slice failed");
//! assert_eq!(slice.len(), 10);
//!
//! // The slice iterator will yield the elements from the slice.
//! let collected: Vec<u32> = slice.iter().collect();
//! let expected: Vec<u32> = (20..30).collect();
//!
//! assert_eq!(collected, expected);
//! ```

use crate::fixed::{
    FixedVec,
    slice::FixedVecSlice,
    traits::{Storable, Word},
};
use dsi_bitstream::prelude::Endianness;
use std::{marker::PhantomData, ops::Deref};

use std::cmp::min;

/// An iterator over the elements of a borrowed [`FixedVec`].
///
/// This struct is created by the [`iter`](FixedVec::iter) method. It is a
/// stateful bitstream reader that decodes values on the fly for both forward
/// and reverse iteration.
///
/// # Examples
///
/// ## Forward iteration
///
/// ```rust
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use compressed_intvec::fixed::{FixedVec, UFixedVec};
///
/// let data: &[u8] = &[1, 2, 3, 4, 5];
/// let vec: UFixedVec<u8> = FixedVec::builder().build(data)?;
/// let mut iter = vec.iter();
///
/// assert_eq!(iter.next(), Some(1));
/// assert_eq!(iter.next(), Some(2));
/// # Ok(())
/// # }
/// ```
///
/// ## Reverse iteration
///
/// ```rust
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use compressed_intvec::fixed::{FixedVec, UFixedVec};
///
/// let data: &[u8] = &[1, 2, 3, 4, 5];
/// let vec: UFixedVec<u8> = FixedVec::builder().build(data)?;
/// let mut iter = vec.iter();
///
/// assert_eq!(iter.next_back(), Some(5));
/// assert_eq!(iter.next_back(), Some(4));
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct FixedVecIter<'a, T, W, E, B>
where
    T: Storable<W>,
    W: Word,
    E: Endianness,
    B: AsRef<[W]>,
{
    vec: &'a FixedVec<T, W, E, B>,
    front_index: usize,
    back_index: usize,

    // State for forward iteration.
    front_window: W,
    front_bits_in_window: usize,
    front_word_index: usize,

    // State for backward iteration.
    back_window: W,
    back_bits_in_window: usize,
    back_word_index: usize,
    _phantom: PhantomData<T>,
}

/// An iterator over non-overlapping, immutable chunks of a [`FixedVec`].
///
/// This struct is created by the [`chunks`](super::FixedVec::chunks) method.
#[derive(Debug)]
pub struct Chunks<'a, T, W, E, B>
where
    T: Storable<W>,
    W: Word,
    E: Endianness,
    B: AsRef<[W]>,
{
    vec: &'a FixedVec<T, W, E, B>,
    chunk_size: usize,
    current_pos: usize,
}

impl<'a, T, W, E, B> FixedVecIter<'a, T, W, E, B>
where
    T: Storable<W>,
    W: Word,
    E: Endianness,
    B: AsRef<[W]>,
{
    /// Creates a new stateful, bidirectional iterator for a given [`FixedVec`].
    pub(super) fn new(vec: &'a FixedVec<T, W, E, B>) -> Self {
        if vec.is_empty() {
            return Self {
                vec,
                front_index: 0,
                back_index: 0,
                front_window: W::ZERO,
                front_bits_in_window: 0,
                front_word_index: 0,
                back_window: W::ZERO,
                back_bits_in_window: 0,
                back_word_index: 0,
                _phantom: PhantomData,
            };
        }

        let limbs = vec.as_limbs();
        let bits_per_word: usize = <W as Word>::BITS;

        // --- Setup forward state ---
        let front_word_index = 1;
        // Pre-load the first word into the forward window.
        let front_window = unsafe { *limbs.get_unchecked(0) };
        let front_bits_in_window = bits_per_word;

        // --- Setup backward state ---
        let total_bits = vec.len() * vec.bit_width();
        let back_word_index = (total_bits.saturating_sub(1)) / bits_per_word;
        // Pre-load the last word into the backward window.
        let back_window = unsafe { *limbs.get_unchecked(back_word_index) };
        // Calculate how many bits in the last word are valid data.
        let back_bits_in_window = total_bits % bits_per_word;
        let back_bits_in_window = if back_bits_in_window == 0 {
            bits_per_word
        } else {
            back_bits_in_window
        };

        Self {
            vec,
            front_index: 0,
            back_index: vec.len(),
            front_window,
            front_bits_in_window,
            front_word_index,
            back_window,
            back_bits_in_window,
            back_word_index,
            _phantom: PhantomData,
        }
    }
}

impl<T, W, E, B> Iterator for FixedVecIter<'_, T, W, E, B>
where
    T: Storable<W>,
    W: Word,
    E: Endianness,
    B: AsRef<[W]>,
{
    type Item = T;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.front_index >= self.back_index {
            return None;
        }
        let index = self.front_index;
        self.front_index += 1;

        let bit_width = self.vec.bit_width();
        // Path for word-sized elements.
        if bit_width == <W as Word>::BITS {
            let val = unsafe { *self.vec.as_limbs().get_unchecked(index) };
            let final_val = if E::IS_BIG { W::from_be(val) } else { val };
            return Some(<T as Storable<W>>::from_word(final_val));
        }

        // Fallback to the standard `get_unchecked` for Big-Endian.
        if E::IS_BIG {
            return Some(unsafe { self.vec.get_unchecked(index) });
        }

        let mask = self.vec.mask;
        // If the current window has enough bits for the next element.
        if self.front_bits_in_window >= bit_width {
            let value = self.front_window & mask;
            self.front_window >>= bit_width;
            self.front_bits_in_window -= bit_width;
            return Some(<T as Storable<W>>::from_word(value));
        }

        // Otherwise, load the next word to replenish the window.
        unsafe {
            let limbs = self.vec.as_limbs();
            let bits_from_old = self.front_bits_in_window;
            let mut result = self.front_window;

            self.front_window = *limbs.get_unchecked(self.front_word_index);
            self.front_word_index += 1;
            result |= self.front_window << bits_from_old;
            let value = result & mask;

            let bits_from_new = bit_width - bits_from_old;
            self.front_window >>= bits_from_new;
            self.front_bits_in_window = <W as Word>::BITS - bits_from_new;

            Some(<T as Storable<W>>::from_word(value))
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.back_index.saturating_sub(self.front_index);
        (remaining, Some(remaining))
    }
}

impl<T, W, E, B> DoubleEndedIterator for FixedVecIter<'_, T, W, E, B>
where
    T: Storable<W>,
    W: Word,
    E: Endianness,
    B: AsRef<[W]>,
{
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.front_index >= self.back_index {
            return None;
        }
        self.back_index -= 1;
        let index = self.back_index;

        if E::IS_BIG || self.vec.bit_width() == <W as Word>::BITS {
            return Some(unsafe { self.vec.get_unchecked(index) });
        }

        let bit_width = self.vec.bit_width();
        let bits_per_word: usize = <W as Word>::BITS;

        if self.back_bits_in_window >= bit_width {
            self.back_bits_in_window -= bit_width;
            let value = (self.back_window >> self.back_bits_in_window) & self.vec.mask;
            return Some(<T as Storable<W>>::from_word(value));
        }

        unsafe {
            let limbs = self.vec.as_limbs();
            let bits_from_old = self.back_bits_in_window;
            let mut result = self.back_window;

            self.back_word_index -= 1;
            self.back_window = *limbs.get_unchecked(self.back_word_index);

            result &= (W::ONE << bits_from_old).wrapping_sub(W::ONE);
            let bits_from_new = bit_width - bits_from_old;
            result <<= bits_from_new;
            result |= self.back_window >> (bits_per_word - bits_from_new);

            self.back_bits_in_window = bits_per_word - bits_from_new;
            Some(<T as Storable<W>>::from_word(result))
        }
    }
}

impl<T, W, E, B> ExactSizeIterator for FixedVecIter<'_, T, W, E, B>
where
    T: Storable<W>,
    W: Word,
    E: Endianness,
    B: AsRef<[W]>,
{
    fn len(&self) -> usize {
        self.back_index.saturating_sub(self.front_index)
    }
}

/// An iterator that consumes an owned [`FixedVec`] and yields its elements.
///
/// This struct is created by the `into_iter` method on `FixedVec`.
///
/// # Implementation
///
/// This is a self-referential struct: the [`FixedVecIter`] borrows from the
/// heap-allocated [`FixedVec`] stored in `_vec_owner`. The `Box` ensures a
/// stable address that won't move, making the `'static` transmute sound.
/// The `iter` field is declared before `_vec_owner` so it is dropped first,
/// though neither type has a custom `Drop` that accesses borrowed data.
pub struct FixedVecIntoIter<T, W, E>
where
    T: Storable<W> + 'static,
    W: Word,
    E: Endianness,
{
    iter: FixedVecIter<'static, T, W, E, Vec<W>>,
    /// Owns the `FixedVec` on the heap. Must outlive `iter`.
    _vec_owner: Box<FixedVec<T, W, E, Vec<W>>>,
}

impl<T, W, E> FixedVecIntoIter<T, W, E>
where
    T: Storable<W> + 'static,
    W: Word,
    E: Endianness,
{
    /// Creates a new consuming iterator from an owned `FixedVec`.
    pub(super) fn new(vec: FixedVec<T, W, E, Vec<W>>) -> Self {
        // Move the FixedVec to the heap so it has a stable address.
        let boxed = Box::new(vec);
        // SAFETY: `boxed` is heap-allocated and will not move. The reference
        // is valid for the lifetime of this struct because `_vec_owner` holds
        // the Box. We transmute to 'static to express this self-referential
        // borrow, which cannot be expressed with Rust lifetimes.
        let iter = unsafe {
            let vec_ref: &'static FixedVec<T, W, E, Vec<W>> =
                std::mem::transmute(&*boxed as &FixedVec<T, W, E, Vec<W>>);
            FixedVecIter::new(vec_ref)
        };
        Self {
            iter,
            _vec_owner: boxed,
        }
    }
}

impl<T, W, E> Iterator for FixedVecIntoIter<T, W, E>
where
    T: Storable<W> + 'static,
    W: Word,
    E: Endianness,
{
    type Item = T;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

impl<T, W, E> DoubleEndedIterator for FixedVecIntoIter<T, W, E>
where
    T: Storable<W> + 'static,
    W: Word,
    E: Endianness,
{
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        self.iter.next_back()
    }
}

impl<T, W, E> ExactSizeIterator for FixedVecIntoIter<T, W, E>
where
    T: Storable<W> + 'static,
    W: Word,
    E: Endianness,
{
    fn len(&self) -> usize {
        self.iter.len()
    }
}

/// An iterator over the elements of a [`FixedVecSlice`].
///
/// This struct is created by the [`iter`](super::slice::FixedVecSlice::iter)
/// method on [`FixedVecSlice`]. It is a stateful bitstream reader that decodes
/// values on the fly for both forward and reverse iteration.
pub struct FixedVecSliceIter<'s, T, W, E, B, V>
where
    T: Storable<W>,
    W: Word,
    E: Endianness,
    B: AsRef<[W]>,
    V: Deref<Target = FixedVec<T, W, E, B>>,
{
    slice: &'s FixedVecSlice<V>,
    front_index: usize, // index relative to slice start
    back_index: usize,  // index relative to slice start

    // State for forward iteration.
    front_window: W,
    front_bits_in_window: usize,
    front_word_index: usize,

    // State for backward iteration.
    back_window: W,
    back_bits_in_window: usize,
    back_word_index: usize,

    _phantom: PhantomData<(T, W, E, B)>,
}

impl<'s, T, W, E, B, V> FixedVecSliceIter<'s, T, W, E, B, V>
where
    T: Storable<W>,
    W: Word,
    E: Endianness,
    B: AsRef<[W]>,
    V: Deref<Target = FixedVec<T, W, E, B>>,
{
    /// Creates a new stateful, bidirectional iterator for a given `FixedVecSlice`.
    pub(super) fn new(slice: &'s FixedVecSlice<V>) -> Self {
        let parent_vec = &slice.parent;
        if slice.is_empty() {
            return Self {
                slice,
                front_index: 0,
                back_index: 0,
                front_window: W::ZERO,
                front_bits_in_window: 0,
                front_word_index: 0,
                back_window: W::ZERO,
                back_bits_in_window: 0,
                back_word_index: 0,
                _phantom: PhantomData,
            };
        }

        let bits_per_word: usize = <W as Word>::BITS;
        let bit_width: usize = parent_vec.bit_width();
        let limbs: &[W] = parent_vec.as_limbs();
        let slice_start_abs: usize = slice.range.start;
        let slice_end_abs: usize = slice.range.end;

        // --- Setup forward state ---
        let start_bit_pos: usize = slice_start_abs * bit_width;
        let start_word_index: usize = start_bit_pos / bits_per_word;
        let start_bit_offset: usize = start_bit_pos % bits_per_word;

        let front_window_raw: W = unsafe { *limbs.get_unchecked(start_word_index) };
        let front_window: W = front_window_raw >> start_bit_offset;
        let front_bits_in_window: usize = bits_per_word - start_bit_offset;
        let front_word_index: usize = start_word_index + 1;

        // --- Setup backward state ---
        let end_bit_pos: usize = slice_end_abs * bit_width;
        let back_word_index: usize = (end_bit_pos.saturating_sub(1)) / bits_per_word;
        let back_window: W = unsafe { *limbs.get_unchecked(back_word_index) };

        let back_bits_in_window = end_bit_pos % bits_per_word;
        let back_bits_in_window = if back_bits_in_window == 0 && end_bit_pos > 0 {
            bits_per_word
        } else {
            back_bits_in_window
        };

        Self {
            slice,
            front_index: 0,
            back_index: slice.len(),
            front_window,
            front_bits_in_window,
            front_word_index,
            back_window,
            back_bits_in_window,
            back_word_index,
            _phantom: PhantomData,
        }
    }
}

impl<T, W, E, B, V> Iterator for FixedVecSliceIter<'_, T, W, E, B, V>
where
    T: Storable<W>,
    W: Word,
    E: Endianness,
    B: AsRef<[W]>,
    V: Deref<Target = FixedVec<T, W, E, B>>,
{
    type Item = T;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.front_index >= self.back_index {
            return None;
        }

        let parent_vec = &self.slice.parent;
        let bit_width = parent_vec.bit_width();
        let mask = parent_vec.mask;

        let abs_index = self.slice.range.start + self.front_index;
        self.front_index += 1;

        if bit_width == <W as Word>::BITS {
            let val = unsafe { *parent_vec.as_limbs().get_unchecked(abs_index) };
            let final_val = if E::IS_BIG { W::from_be(val) } else { val };
            return Some(<T as Storable<W>>::from_word(final_val));
        }

        if E::IS_BIG {
            return Some(unsafe { parent_vec.get_unchecked(abs_index) });
        }

        if self.front_bits_in_window >= bit_width {
            let value = self.front_window & mask;
            self.front_window >>= bit_width;
            self.front_bits_in_window -= bit_width;
            return Some(<T as Storable<W>>::from_word(value));
        }

        unsafe {
            let limbs = parent_vec.as_limbs();
            let bits_from_old = self.front_bits_in_window;
            let mut result = self.front_window;

            self.front_window = *limbs.get_unchecked(self.front_word_index);
            self.front_word_index += 1;
            result |= self.front_window << bits_from_old;
            let value = result & mask;

            let bits_from_new = bit_width - bits_from_old;
            self.front_window >>= bits_from_new;
            self.front_bits_in_window = <W as Word>::BITS - bits_from_new;

            Some(<T as Storable<W>>::from_word(value))
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.back_index.saturating_sub(self.front_index);
        (remaining, Some(remaining))
    }
}

impl<T, W, E, B, V> DoubleEndedIterator for FixedVecSliceIter<'_, T, W, E, B, V>
where
    T: Storable<W>,
    W: Word,
    E: Endianness,
    B: AsRef<[W]>,
    V: Deref<Target = FixedVec<T, W, E, B>>,
{
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.front_index >= self.back_index {
            return None;
        }
        self.back_index -= 1;
        let abs_index = self.slice.range.start + self.back_index;
        let parent_vec = &self.slice.parent;

        if E::IS_BIG || parent_vec.bit_width() == <W as Word>::BITS {
            return Some(unsafe { parent_vec.get_unchecked(abs_index) });
        }

        let bit_width = parent_vec.bit_width();
        let bits_per_word: usize = <W as Word>::BITS;

        if self.back_bits_in_window >= bit_width {
            self.back_bits_in_window -= bit_width;
            let value = (self.back_window >> self.back_bits_in_window) & parent_vec.mask;
            return Some(<T as Storable<W>>::from_word(value));
        }

        unsafe {
            let limbs = parent_vec.as_limbs();
            let bits_from_old = self.back_bits_in_window;
            let mut result = self.back_window;

            self.back_word_index -= 1;
            self.back_window = *limbs.get_unchecked(self.back_word_index);

            result &= (W::ONE << bits_from_old).wrapping_sub(W::ONE);
            let bits_from_new = bit_width - bits_from_old;
            result <<= bits_from_new;
            result |= self.back_window >> (bits_per_word - bits_from_new);

            self.back_bits_in_window = bits_per_word - bits_from_new;
            Some(<T as Storable<W>>::from_word(result))
        }
    }
}

impl<T, W, E, B, V> ExactSizeIterator for FixedVecSliceIter<'_, T, W, E, B, V>
where
    T: Storable<W>,
    W: Word,
    E: Endianness,
    B: AsRef<[W]>,
    V: Deref<Target = FixedVec<T, W, E, B>>,
{
    fn len(&self) -> usize {
        self.back_index.saturating_sub(self.front_index)
    }
}

impl<'a, T, W, E, B> Chunks<'a, T, W, E, B>
where
    T: Storable<W>,
    W: Word,
    E: Endianness,
    B: AsRef<[W]>,
{
    /// Creates a new `Chunks` iterator.
    pub(super) fn new(vec: &'a FixedVec<T, W, E, B>, chunk_size: usize) -> Self {
        assert!(chunk_size != 0, "chunk_size cannot be zero");
        Self {
            vec,
            chunk_size,
            current_pos: 0,
        }
    }
}

impl<'a, T, W, E, B> Iterator for Chunks<'a, T, W, E, B>
where
    T: Storable<W>,
    W: Word,
    E: Endianness,
    B: AsRef<[W]>,
{
    type Item = FixedVecSlice<&'a FixedVec<T, W, E, B>>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.current_pos >= self.vec.len() {
            return None;
        }

        let len = min(self.chunk_size, self.vec.len() - self.current_pos);
        let slice = FixedVecSlice::new(self.vec, self.current_pos..self.current_pos + len);
        self.current_pos += len;

        Some(slice)
    }
}

/// An iterator over overlapping sub-slices of a [`FixedVec`].
///
/// This struct is created by the [`windows`](super::FixedVec::windows) method.
pub struct Windows<'a, T, W, E, B>
where
    T: Storable<W>,
    W: Word,
    E: Endianness,
    B: AsRef<[W]>,
{
    vec: &'a FixedVec<T, W, E, B>,
    size: usize,
    current_pos: usize,
}

impl<'a, T, W, E, B> Windows<'a, T, W, E, B>
where
    T: Storable<W>,
    W: Word,
    E: Endianness,
    B: AsRef<[W]>,
{
    /// Creates a new `Windows` iterator.
    pub(super) fn new(vec: &'a FixedVec<T, W, E, B>, size: usize) -> Self {
        Self {
            vec,
            size,
            current_pos: 0,
        }
    }
}

impl<'a, T, W, E, B> Iterator for Windows<'a, T, W, E, B>
where
    T: Storable<W>,
    W: Word,
    E: Endianness,
    B: AsRef<[W]>,
{
    type Item = FixedVecSlice<&'a FixedVec<T, W, E, B>>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.current_pos + self.size > self.vec.len() {
            return None;
        }

        let slice = FixedVecSlice::new(self.vec, self.current_pos..self.current_pos + self.size);
        self.current_pos += 1;

        Some(slice)
    }
}

/// An unchecked iterator over the elements of a [`FixedVec`].
///
/// This struct is created by the [`iter_unchecked`](super::FixedVec::iter_unchecked)
/// method. It does not perform any bounds checking.
///
/// # Safety
///
/// The iterator is safe to use only if it is guaranteed that it will not
/// be advanced beyond the end of the vector.
pub struct FixedVecUncheckedIter<'a, T, W, E, B>
where
    T: Storable<W>,
    W: Word,
    E: Endianness,
    B: AsRef<[W]>,
{
    iter: FixedVecIter<'a, T, W, E, B>,
}

impl<'a, T, W, E, B> FixedVecUncheckedIter<'a, T, W, E, B>
where
    T: Storable<W>,
    W: Word,
    E: Endianness,
    B: AsRef<[W]>,
{
    /// Creates a new `FixedVecUncheckedIter`.
    pub(super) fn new(vec: &'a FixedVec<T, W, E, B>) -> Self {
        Self {
            iter: FixedVecIter::new(vec),
        }
    }

    /// Returns the next element without bounds checking.
    ///
    /// # Safety
    ///
    /// Calling this method when the iterator is exhausted is undefined behavior.
    #[inline]
    pub unsafe fn next_unchecked(&mut self) -> T {
        // The underlying FixedVecIter is already highly optimized.
        // The primary gain here is removing the check in `next()`.
        unsafe { self.iter.next().unwrap_unchecked() }
    }

    /// Returns the next element from the back without bounds checking.
    ///
    /// # Safety
    ///
    /// Calling this method when the iterator is exhausted is undefined behavior.
    #[inline]
    pub unsafe fn next_back_unchecked(&mut self) -> T {
        unsafe { self.iter.next_back().unwrap_unchecked() }
    }
}