Skip to content

feat: ExactSizeIterator impl for Chunks #1037

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions src/groupbylazy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ use alloc::vec::{self, Vec};
use std::cell::{Cell, RefCell};
use std::fmt::Debug;

use crate::size_hint;

/// A trait to unify `FnMut` for `ChunkBy` with the chunk key in `IntoChunks`
trait KeyFunction<A> {
type Key;
Expand Down Expand Up @@ -583,6 +585,27 @@ where
}
}

impl<I> IntoChunks<I>
where
I: ExactSizeIterator,
{
fn len(&self) -> usize {
// chunk_size cannot be null as it is checked in `Itertools::chunks`
let chunk_size = self.inner.borrow().key.size;
debug_assert!(chunk_size != 0);

let iter_len = self.inner.borrow().iter.len();
// TODO: MSRV of itertools is 1.63 when `uint::div_ceil` was stabilized in 1.73
let d = iter_len / chunk_size;
let r = iter_len % chunk_size;
if r > 0 {
d + 1
} else {
d
}
}
}

impl<'a, I> IntoIterator for &'a IntoChunks<I>
where
I: Iterator,
Expand Down Expand Up @@ -637,11 +660,30 @@ where
first: Some(elt),
})
}

fn size_hint(&self) -> (usize, Option<usize>) {
// chunk_size cannot be null as it is checked in `Itertools::chunks`
let chunk_size = self.parent.inner.borrow().key.size;
debug_assert!(chunk_size != 0);

size_hint::div_ceil_scalar(self.parent.inner.borrow().iter.size_hint(), chunk_size)
}
}

impl<'a, I> ExactSizeIterator for Chunks<'a, I>
where
I: ExactSizeIterator,
I::Item: 'a,
{
fn len(&self) -> usize {
self.parent.len()
}
}

/// An iterator for the elements in a single chunk.
///
/// Iterator element type is `I::Item`.
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
#[derive(Debug)]
pub struct Chunk<'a, I>
where
Expand Down
22 changes: 22 additions & 0 deletions src/size_hint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,21 @@ pub fn mul_scalar(sh: SizeHint, x: usize) -> SizeHint {
(low, hi)
}

/// Correct ceiling division by `x` with a `SizeHint`.
#[inline]
#[track_caller]
pub fn div_ceil_scalar(sh: SizeHint, x: usize) -> SizeHint {
let (low, hi) = sh;
let (dlow, dhi) = (low / x, hi.map(|hi| hi / x));
let (rlow, rhi) = (low % x, hi.map(|hi| hi % x));

let low = if rlow > 0 { dlow + 1 } else { dlow };
let hi = dhi
.and_then(|dhi| rhi.map(|rhi| (dhi, rhi)))
.map(|(dhi, rhi)| if rhi > 0 { dhi + 1 } else { dhi });
(low, hi)
}

/// Return the maximum
#[inline]
pub fn max(a: SizeHint, b: SizeHint) -> SizeHint {
Expand Down Expand Up @@ -92,3 +107,10 @@ fn mul_size_hints() {
assert_eq!(mul((3, Some(4)), (usize::MAX, None)), (usize::MAX, None));
assert_eq!(mul((3, None), (0, Some(0))), (0, Some(0)));
}

#[test]
fn div_ceil_size_scalar() {
assert_eq!(div_ceil_scalar((3, Some(4)), 2), (2, Some(2)));
assert_eq!(div_ceil_scalar((3, Some(4)), usize::MAX), (1, Some(1)));
assert_eq!(div_ceil_scalar((3, None), 2), (2, None));
}
42 changes: 42 additions & 0 deletions tests/test_std.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1034,6 +1034,48 @@ fn chunks() {
}
}

#[test]
fn chunks_len() {
const TEST_CHUNK_SIZE: usize = 2;

// test `<Chunks as Iterator>::size_hint`
// (buffer, len of chunks)
[
(vec![], (0, Some(0))),
(vec![1], (1, Some(1))),
(vec![1, 2], (1, Some(1))),
(vec![1, 2, 3], (2, Some(2))),
(vec![1, 2, 3, 4], (2, Some(2))),
]
.iter()
.for_each(|(buf, expected_hint)| {
assert_eq!(
buf.into_iter()
.chunks(TEST_CHUNK_SIZE)
.into_iter()
.size_hint(),
*expected_hint
)
});

// test `<Chunks as ExactSizeIterator>::len`
// (buffer, len of chunks)
[
(vec![], 0),
(vec![1], 1),
(vec![1, 2], 1),
(vec![1, 2, 3], 2),
(vec![1, 2, 3, 4], 2),
]
.iter()
.for_each(|(buf, expected_len)| {
assert_eq!(
buf.into_iter().chunks(TEST_CHUNK_SIZE).into_iter().len(),
*expected_len
)
});
}

#[test]
fn concat_empty() {
let data: Vec<Vec<()>> = Vec::new();
Expand Down