Skip to content

Commit

Permalink
Merge pull request rust-embedded#447 from rlee287/extend_for_deque
Browse files Browse the repository at this point in the history
Impl Extend for Deque
  • Loading branch information
reitermarkus authored Jan 26, 2024
2 parents 6d62cb2 + 1d91e64 commit b1f040d
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
- Added `is_full`, `recent_index`, `oldest`, and `oldest_index` to `HistoryBuffer`
- Added infallible conversions from arrays to `Vec`.
- Added `Vec::spare_capacity_mut`.
- Added `Extend` impls for `Deque`.

### Changed

Expand Down
39 changes: 39 additions & 0 deletions src/deque.rs
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,20 @@ impl<T: fmt::Debug, const N: usize> fmt::Debug for Deque<T, N> {
}
}

/// As with the standard library's `VecDeque`, items are added via `push_back`.
impl<T, const N: usize> Extend<T> for Deque<T, N> {
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
for item in iter {
self.push_back(item).ok().unwrap();
}
}
}
impl<'a, T: 'a + Copy, const N: usize> Extend<&'a T> for Deque<T, N> {
fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
self.extend(iter.into_iter().copied())
}
}

/// An iterator that moves out of a [`Deque`].
///
/// This struct is created by calling the `into_iter` method.
Expand Down Expand Up @@ -661,6 +675,31 @@ mod tests {
assert_eq!(v.back_mut(), None);
}

#[test]
fn extend() {
let mut v: Deque<i32, 4> = Deque::new();
v.extend(&[1, 2, 3]);
assert_eq!(v.pop_front().unwrap(), 1);
assert_eq!(v.pop_front().unwrap(), 2);
assert_eq!(*v.front().unwrap(), 3);

v.push_back(4).unwrap();
v.extend(&[5, 6]);
assert_eq!(v.pop_front().unwrap(), 3);
assert_eq!(v.pop_front().unwrap(), 4);
assert_eq!(v.pop_front().unwrap(), 5);
assert_eq!(v.pop_front().unwrap(), 6);
assert!(v.pop_front().is_none());
}

#[test]
#[should_panic]
fn extend_panic() {
let mut v: Deque<i32, 4> = Deque::new();
// Is too many elements -> should panic
v.extend(&[1, 2, 3, 4, 5]);
}

#[test]
fn iter() {
let mut v: Deque<i32, 4> = Deque::new();
Expand Down

0 comments on commit b1f040d

Please sign in to comment.