Skip to content

Commit

Permalink
collections: Simplify VecDeque::is_empty
Browse files Browse the repository at this point in the history
Improve is_empty on the VecDeque and its iterators by just comparing
tail and head; this saves a few instructions (to be able to remove the
`& (size - 1)` computation, it would have to know that size is a power of two).
  • Loading branch information
bluss committed Dec 4, 2016
1 parent 7ba7622 commit 343b4c3
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
20 changes: 16 additions & 4 deletions src/libcollections/vec_deque.rs
Expand Up @@ -810,7 +810,7 @@ impl<T> VecDeque<T> {
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn is_empty(&self) -> bool {
self.len() == 0
self.tail == self.head
}

/// Create a draining iterator that removes the specified range in the
Expand Down Expand Up @@ -1916,7 +1916,11 @@ impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
impl<'a, T> ExactSizeIterator for Iter<'a, T> {
fn is_empty(&self) -> bool {
self.head == self.tail
}
}

#[unstable(feature = "fused", issue = "35602")]
impl<'a, T> FusedIterator for Iter<'a, T> {}
Expand Down Expand Up @@ -1980,7 +1984,11 @@ impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
impl<'a, T> ExactSizeIterator for IterMut<'a, T> {
fn is_empty(&self) -> bool {
self.head == self.tail
}
}

#[unstable(feature = "fused", issue = "35602")]
impl<'a, T> FusedIterator for IterMut<'a, T> {}
Expand Down Expand Up @@ -2017,7 +2025,11 @@ impl<T> DoubleEndedIterator for IntoIter<T> {
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T> ExactSizeIterator for IntoIter<T> {}
impl<T> ExactSizeIterator for IntoIter<T> {
fn is_empty(&self) -> bool {
self.inner.is_empty()
}
}

#[unstable(feature = "fused", issue = "35602")]
impl<T> FusedIterator for IntoIter<T> {}
Expand Down
21 changes: 21 additions & 0 deletions src/libcollectionstest/vec_deque.rs
Expand Up @@ -1007,3 +1007,24 @@ fn assert_covariance() {
d
}
}

#[test]
fn test_is_empty() {
let mut v = VecDeque::<i32>::new();
assert!(v.is_empty());
assert!(v.iter().is_empty());
assert!(v.iter_mut().is_empty());
v.extend(&[2, 3, 4]);
assert!(!v.is_empty());
assert!(!v.iter().is_empty());
assert!(!v.iter_mut().is_empty());
while let Some(_) = v.pop_front() {
assert_eq!(v.is_empty(), v.len() == 0);
assert_eq!(v.iter().is_empty(), v.iter().len() == 0);
assert_eq!(v.iter_mut().is_empty(), v.iter_mut().len() == 0);
}
assert!(v.is_empty());
assert!(v.iter().is_empty());
assert!(v.iter_mut().is_empty());
assert!(v.into_iter().is_empty());
}

0 comments on commit 343b4c3

Please sign in to comment.