mirror of
https://github.com/rust-lang/rust.git
synced 2024-11-22 14:55:26 +00:00
Auto merge of #57974 - llogiq:vec-deque-try-fold, r=alexcrichton
override `VecDeque`'s `Iter::try_fold` This should improve performance (wherever it is used), but I haven't found the time to benchmark it yet.
This commit is contained in:
commit
147311c5fc
@ -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;
|
||||
@ -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")]
|
||||
|
@ -113,6 +113,7 @@
|
||||
#![feature(slice_partition_dedup)]
|
||||
#![feature(maybe_uninit)]
|
||||
#![feature(alloc_layout_extra)]
|
||||
#![feature(try_trait)]
|
||||
|
||||
// Allow testing this library
|
||||
|
||||
|
@ -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)));
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user