avshyz
avshyz

Reputation: 135

How to iterate over itertools::chunks

I'm a new rustacean, so my code's quality is questionable. While trying to get the ropes of rust, I've come across the following problem.

I have a vector of bits (bools), and I want to convert then into a vector of bytes (u8)

My first implementation looked like that

let mut res: Vec<u8> = vec![];
let mut curr = 0;
for (idx, &bit) in bits.iter().enumerate() {
    let x = (idx % 8) as u8;
    if idx % 8 != 0 || idx == 0 {
        curr = set_bit_at(curr, (7 - (idx % 8)) as u32, bit).unwrap();
    } else {
        res.push(curr);
        curr = 0
    }
}
res.push(curr);

It worked, but It felt pretty ugly, so I've tried to implement it using the crate itertools.

let res = bits.iter()
    .chunks(8)
    .map(|split_byte: Vec<u8>| {
        split_byte.fold(0, |res, &bit| (res << 1) | (bit as u8))
    })
    .collect();

It sure looks nicer, but sadly - it didn't work.

Even though it seems as if chunks's return type seems to be an iterator, this line produced the following error

error[E0599]: no method named `map` found for type `bits::itertools::IntoChunks<std::slice::Iter<'_, bool>>` in the current scope

Could anyone tell what did I do wrong?

Upvotes: 7

Views: 3997

Answers (1)

NougatRillettes
NougatRillettes

Reputation: 463

I believe you have misread the doc here. The right part for you is here. Where you'll see that (emphasis mine):

Return an iterable that can chunk the iterator.

IntoChunks is based on GroupBy: it is iterable (implements IntoIterator, not Iterator), and it only buffers if several chunk iterators are alive at the same time.

Hence, you need to use into_iter before your map.

Upvotes: 10

Related Questions