Skip to content

Commit 65c553d

Browse files
committed
Auto merge of #530 - ToMe25:fix_set_diff_size_hint, r=Amanieu
Improve Set Difference size_hint lower bound This PR makes the Set `Difference` iterator generate a non-zero lower bound in some situations. Specifically, it now returns a non-zero lower bound if the `difference` method is called on a larger set with a smaller set. That is because in those cases the fact that sets can't really contains duplicates\* guarantees that a minimum of `self.len() - other.len()` items will be returned by the iterator. \* Well, they can, but that is already documented to be causing a random mess This implementation has the disadvantage that a single `next()` call may reduce the lower bound by more than one. Every size hint generated, even the first largest one, is guaranteed to be correct, but it may be confusing if one `next()` call causes the lower bound to drop by more than one. This could be avoided by storing the minimum number of resulting elements in the iterator and subtracting one each time `next()` is called, but I don't think its worth the added complexity.
2 parents a34158c + f4361bc commit 65c553d

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

src/set.rs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1851,6 +1851,7 @@ where
18511851
let (_, upper) = self.iter.size_hint();
18521852
(0, upper)
18531853
}
1854+
18541855
#[cfg_attr(feature = "inline-more", inline)]
18551856
fn fold<B, F>(self, init: B, mut f: F) -> B
18561857
where
@@ -1916,9 +1917,10 @@ where
19161917

19171918
#[cfg_attr(feature = "inline-more", inline)]
19181919
fn size_hint(&self) -> (usize, Option<usize>) {
1919-
let (_, upper) = self.iter.size_hint();
1920-
(0, upper)
1920+
let (lower, upper) = self.iter.size_hint();
1921+
(lower.saturating_sub(self.other.len()), upper)
19211922
}
1923+
19221924
#[cfg_attr(feature = "inline-more", inline)]
19231925
fn fold<B, F>(self, init: B, mut f: F) -> B
19241926
where
@@ -1975,10 +1977,12 @@ where
19751977
fn next(&mut self) -> Option<&'a T> {
19761978
self.iter.next()
19771979
}
1980+
19781981
#[cfg_attr(feature = "inline-more", inline)]
19791982
fn size_hint(&self) -> (usize, Option<usize>) {
19801983
self.iter.size_hint()
19811984
}
1985+
19821986
#[cfg_attr(feature = "inline-more", inline)]
19831987
fn fold<B, F>(self, init: B, f: F) -> B
19841988
where
@@ -2048,10 +2052,12 @@ where
20482052
fn next(&mut self) -> Option<&'a T> {
20492053
self.iter.next()
20502054
}
2055+
20512056
#[cfg_attr(feature = "inline-more", inline)]
20522057
fn size_hint(&self) -> (usize, Option<usize>) {
20532058
self.iter.size_hint()
20542059
}
2060+
20552061
#[cfg_attr(feature = "inline-more", inline)]
20562062
fn fold<B, F>(self, init: B, f: F) -> B
20572063
where

0 commit comments

Comments
 (0)