Skip to content

Commit

Permalink
override VecDeque's Iter::try_fold
Browse files Browse the repository at this point in the history
  • Loading branch information
llogiq committed Jan 30, 2019
1 parent 106b3e9 commit b062b75
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/liballoc/collections/vec_deque.rs
Expand Up @@ -12,7 +12,7 @@ use core::fmt;
use core::iter::{repeat_with, FromIterator, FusedIterator};
use core::mem;
use core::ops::Bound::{Excluded, Included, Unbounded};
use core::ops::{Index, IndexMut, RangeBounds};
use core::ops::{Index, IndexMut, RangeBounds, Try};
use core::ptr;
use core::ptr::NonNull;
use core::slice;
Expand Down Expand Up @@ -2172,6 +2172,14 @@ impl<'a, T> Iterator for Iter<'a, T> {
accum = front.iter().fold(accum, &mut f);
back.iter().fold(accum, &mut f)
}

fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where
Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
{
let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail);
let accum = front.iter().try_fold(init, &mut f)?;
back.iter().try_fold(accum, &mut f)
}
}

#[stable(feature = "rust1", since = "1.0.0")]
Expand Down
1 change: 1 addition & 0 deletions src/liballoc/lib.rs
Expand Up @@ -113,6 +113,7 @@
#![feature(slice_partition_dedup)]
#![feature(maybe_uninit)]
#![feature(alloc_layout_extra)]
#![feature(try_trait)]

// Allow testing this library

Expand Down
37 changes: 37 additions & 0 deletions src/liballoc/tests/vec_deque.rs
Expand Up @@ -1433,3 +1433,40 @@ fn test_rotate_right_random() {
}
}
}

#[test]
fn test_try_fold_empty() {
assert_eq!(Some(0), VecDeque::<u32>::new().iter().try_fold(0, |_, _| None));
}

#[test]
fn test_try_fold_none() {
let v: VecDeque<u32> = (0..12).collect();
assert_eq!(None, v.into_iter().try_fold(0, |a, b|
if b < 11 { Some(a + b) } else { None }));
}

#[test]
fn test_try_fold_ok() {
let v: VecDeque<u32> = (0..12).collect();
assert_eq!(Ok::<_, ()>(66), v.into_iter().try_fold(0, |a, b| Ok(a + b)));
}

#[test]
fn test_try_fold_unit() {
let v: VecDeque<()> = std::iter::repeat(()).take(42).collect();
assert_eq!(Some(()), v.into_iter().try_fold((), |(), ()| Some(())));
}

#[test]
fn test_try_fold_rotated() {
let mut v: VecDeque<_> = (0..12).collect();
for n in 0..10 {
if n & 1 == 0 {
v.rotate_left(n);
} else {
v.rotate_right(n);
}
assert_eq!(Ok::<_, ()>(66), v.iter().try_fold(0, |a, b| Ok(a + b)));
}
}

0 comments on commit b062b75

Please sign in to comment.