itertools icon indicating copy to clipboard operation
itertools copied to clipboard

`.by_ref().chunks()` consumes one extra element than expected

Open ronnodas opened this issue 5 months ago • 0 comments

If I use iter.by_ref().chunks(n) and consume k of the chunks, I expect exactly k*n items to be consumed from iter. But this is not the case as the failing assertion in the following code (playground link) shows:

fn main() {
    let mut iter = 1_u32..10;
    {
        let chunks = iter.by_ref().chunks(2);
        let chunk = chunks.into_iter().next().unwrap();
        assert_eq!(chunk.count(), 2)
    }

    assert_eq!(iter.next(), Some(3)) // actually yields Some(4)
}

If the number of chunks to be consumed is known ahead of time then we can use by_ref().take().chunks() as a workaround, but this doesn't work in general.

ronnodas avatar Jun 20 '25 22:06 ronnodas