]> git.lizzy.rs Git - rust.git/commitdiff
override `VecDeque`'s `Iter::try_fold`
authorAndre Bogus <bogusandre@gmail.com>
Tue, 29 Jan 2019 15:15:02 +0000 (16:15 +0100)
committerAndre Bogus <bogusandre@gmail.com>
Wed, 30 Jan 2019 08:11:17 +0000 (09:11 +0100)
src/liballoc/collections/vec_deque.rs
src/liballoc/lib.rs
src/liballoc/tests/vec_deque.rs

index b3f7ef5fd6eccf18c24cea8a383ff80c6a3c55b5..579d7de96e6dab8e168141d1e6cabc1163b92991 100644 (file)
@@ -12,7 +12,7 @@
 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;
@@ -2172,6 +2172,14 @@ fn fold<Acc, F>(self, mut accum: Acc, mut f: F) -> Acc
         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")]
index d2ff1bae635616c050cb0a5b40e886abc94dbc19..5165a7ca5a8f330e60177f074c6590ff409cdc3d 100644 (file)
 #![feature(slice_partition_dedup)]
 #![feature(maybe_uninit)]
 #![feature(alloc_layout_extra)]
+#![feature(try_trait)]
 
 // Allow testing this library
 
index 76831ba65e3b8ff27f8196565f142b951e385013..c9d16a06b4773cee9bd474c43619c2778f50672b 100644 (file)
@@ -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)));
+    }
+}