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
use std::iter;
use std::mem;
use std::ops::Range;
use std::slice;
use std::vec;

use crate::BitVec;
use crate::BITS;

impl BitVec {
    /// Returns an iterator over the elements of the vector in order.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use std::collections::BitVec;
    ///
    /// let bv = BitVec::from_bytes(&[0b01110100, 0b10010010]);
    /// assert_eq!(bv.iter().filter(|x| *x).count(), 7);
    /// ```
    #[inline]
    pub fn iter(&self) -> Iter<'_> {
        Iter {
            bit_vec: self,
            idx: 0..self.len(),
        }
    }
}

/// An iterator for `BitVec`.
#[derive(Clone)]
pub struct Iter<'a> {
    bit_vec: &'a BitVec,
    idx: Range<usize>,
}

impl<'a> Iterator for Iter<'a> {
    type Item = bool;

    #[inline]
    fn next(&mut self) -> Option<bool> {
        self.bit_vec.get(self.idx.next()?)
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.idx.size_hint()
    }
}

impl<'a> DoubleEndedIterator for Iter<'a> {
    #[inline]
    fn next_back(&mut self) -> Option<bool> {
        self.bit_vec.get(self.idx.next_back()?)
    }
}

impl<'a> ExactSizeIterator for Iter<'a> {}

impl<'a> IntoIterator for &'a BitVec {
    type Item = bool;
    type IntoIter = Iter<'a>;

    #[inline]
    fn into_iter(self) -> Iter<'a> {
        self.iter()
    }
}

impl BitVec {
    #[inline]
    pub fn ones_from(&self, from: usize) -> Ones<'_> {
        let (byte, bit) = (from / BITS, from % BITS);
        let mask = (!0) << bit;
        let mut iter = self.as_bytes()[byte..].iter().copied();
        let (current, _) = usize_from_bytes(&mut iter);
        InnerOnes {
            base: byte * BITS,
            current: current & mask,
            iter,
        }
    }

    #[inline]
    pub fn into_ones(self) -> IntoOnes {
        let mut iter = self.into_bytes().into_iter();
        let (current, _) = usize_from_bytes(&mut iter);
        InnerOnes {
            base: 0,
            current,
            iter,
        }
    }
}

pub type Ones<'a> = InnerOnes<iter::Copied<slice::Iter<'a, u8>>>;
pub type IntoOnes = InnerOnes<vec::IntoIter<u8>>;

#[derive(Clone)]
pub struct InnerOnes<I> {
    base: usize,
    current: usize,
    iter: I,
}

impl<I: Iterator<Item = u8>> Iterator for InnerOnes<I> {
    type Item = usize;

    #[inline]
    fn next(&mut self) -> Option<usize> {
        let mut c = self.current;
        while c == 0 {
            let (next, done) = usize_from_bytes(&mut self.iter);
            if done {
                return None;
            }
            self.base += BITS * mem::size_of::<usize>();
            c = next;
        }

        let lsb = c.trailing_zeros();
        self.current = c & (c - 1);
        Some(self.base + lsb as usize)
    }
}

/// Extract a `usize` from an iterator over bytes.
///
/// It helps our iterator performance to pull bits from a native word at a time.
#[inline]
fn usize_from_bytes(iter: &mut impl Iterator<Item = u8>) -> (usize, bool) {
    let mut n = 0;
    for i in 0..mem::size_of::<usize>() {
        match iter.next() {
            Some(b) => n |= usize::from(b) << (i * BITS),
            None => return (n, i == 0),
        }
    }
    (n, false)
}

#[test]
fn iter_ones_from() {
    let len = 5000;

    let zeros = BitVec::from_elem(len, false);
    assert_eq!(zeros.ones_from(0).next(), None);

    let ones = BitVec::from_elem(len, true);
    let mut iter = ones.ones_from(0);
    for i in 0..len {
        assert_eq!(iter.next(), Some(i));
        assert_eq!(ones.ones_from(i).next(), Some(i));
    }

    let mut halves = BitVec::from_elem(len * 2, false);
    for i in 0..len {
        halves.set(i * 2, true);
    }
    let mut iter = halves.ones_from(0);
    for i in 0..len {
        assert_eq!(iter.next(), Some(i * 2));
        assert_eq!(halves.ones_from(i * 2).next(), Some(i * 2));
        if i > 0 {
            assert_eq!(halves.ones_from(i * 2 - 1).next(), Some(i * 2));
        }
        assert_eq!(halves.ones_from(i).next(), Some(i + (i % 2)));
    }

    let mut sparse = BitVec::from_elem(len * 101, false);
    for i in 0..len {
        sparse.set(i * 101, true);
    }
    let mut iter = sparse.ones_from(0);
    for i in 0..len {
        let i101 = i * 101;
        assert_eq!(iter.next(), Some(i101));
        if i > 0 {
            for j in i101 - 100..=i101 {
                assert_eq!(sparse.ones_from(j).next(), Some(i101));
            }
        }
    }
}

#[test]
fn iter_into_ones() {
    let len = 5000;

    let zeros = BitVec::from_elem(len, false);
    assert_eq!(zeros.into_ones().next(), None);

    let ones = BitVec::from_elem(len, true);
    let mut iter = ones.into_ones();
    for i in 0..len {
        assert_eq!(iter.next(), Some(i));
    }

    let mut halves = BitVec::from_elem(len * 2, false);
    for i in 0..len {
        halves.set(i * 2, true);
    }
    let mut iter = halves.into_ones();
    for i in 0..len {
        assert_eq!(iter.next(), Some(i * 2));
    }

    let mut sparse = BitVec::from_elem(len * 101, false);
    for i in 0..len {
        sparse.set(i * 101, true);
    }
    let mut iter = sparse.into_ones();
    for i in 0..len {
        assert_eq!(iter.next(), Some(i * 101));
    }
}