-
Notifications
You must be signed in to change notification settings - Fork 319
Added set_size_hint
method
#341
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
base: master
Are you sure you want to change the base?
Conversation
Update, | ||
WhileSome, | ||
}; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I also rearranged these into alphabetical order, while I was adding one anyway.
Thank you for your contribution! I'm convinced this is a compelling use-case, but have a few concerns:
|
This seems like a useful functionality.
In any case, +1 |
I agree that this looks useful. Could/should we |
Just to note that try_fold is unfortunately out of bounds for itertools until it can be implemented in stable Rust (we can't name the Try trait in stable Rust yet). |
@phimuemue I'd skip that check, it risks disrupting the program as much as it helps |
I agree! @peterjoel, what do you think of this approach? pub struct SetSizeHint<I> {
iter: I,
lower: usize,
upper: Option<usize>,
}
impl<I> Iterator for SetSizeHint<I>
where
I: Iterator,
{
type Item = I::Item;
#[inline(always)]
fn next(&mut self) -> Option<Self::Item> {
let next = self.iter.next();
if next.is_some() {
self.lower = self.lower.saturating_sub(1);
if let Some(ref mut upper) = self.upper {
*upper = upper.saturating_sub(1);
}
}
next
}
#[inline(always)]
fn fold<B, F>(mut self, init: B, mut f: F) -> B
where
Self: Sized,
F: FnMut(B, Self::Item) -> B,
{
let mut consumed: usize = 0;
let result = self.iter.fold(init, |acc, x| {
consumed = consumed.saturating_add(1);
f(acc, x)
});
self.lower = self.lower.saturating_sub(consumed);
if let Some(ref mut upper) = self.upper {
*upper = upper.saturating_sub(consumed);
}
result
}
#[inline(always)]
fn size_hint(&self) -> (usize, Option<usize>) {
(self.lower, self.upper)
}
} There are three notable changes:
|
I'd want to make sure that the decrement is mostly optimised out in cases where the size hint ends up not being used. |
In these cases probably fold/for_each could be used, and also maybe one could avoid calling |
That's true. There is no reason to use the method if you don't need it. |
@jswrenn The methods you refer to, which use |
Sometimes there is not enough information available for adapters to correctly deduce a useful size hint. However, a developer might have more information and this new iterator method allows them to express it.
A motivating example from the code:
I am not 100% happy with the method name,
set_size_hint
, and there are alternatives in which only one of the bounds is set at a time.