-
Notifications
You must be signed in to change notification settings - Fork 13.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add Iterator::array_windows()
#92394
Closed
+222
−3
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,102 @@ | ||
use crate::iter::{ExactSizeIterator, Fuse, FusedIterator, Iterator, TrustedLen}; | ||
|
||
use crate::array; | ||
|
||
/// An iterator over all contiguous windows of length `N`. The windows overlap. | ||
/// If the iterator is shorter than `N`, the iterator returns no values. | ||
/// | ||
/// This `struct` is created by [`Iterator::array_windows`]. See its | ||
/// documentation for more. | ||
#[derive(Debug, Clone)] | ||
#[must_use = "iterators are lazy and do nothing unless consumed"] | ||
#[unstable(feature = "iter_array_windows", reason = "recently added", issue = "none")] | ||
pub struct ArrayWindows<I, const N: usize> | ||
where | ||
I: Iterator, | ||
I::Item: Clone, | ||
{ | ||
iter: Fuse<I>, | ||
last: Option<[I::Item; N]>, | ||
} | ||
|
||
impl<I, const N: usize> ArrayWindows<I, N> | ||
where | ||
I: Iterator, | ||
I::Item: Clone, | ||
{ | ||
#[inline] | ||
pub(in crate::iter) fn new(iter: I) -> Self { | ||
assert!(N != 0); | ||
Self { iter: iter.fuse(), last: None } | ||
} | ||
} | ||
|
||
#[unstable(feature = "iter_array_windows", reason = "recently added", issue = "none")] | ||
impl<I: Iterator, const N: usize> Iterator for ArrayWindows<I, N> | ||
where | ||
I: Iterator, | ||
I::Item: Clone, | ||
{ | ||
type Item = [I::Item; N]; | ||
|
||
#[inline] | ||
fn next(&mut self) -> Option<Self::Item> { | ||
let Self { iter, last } = self; | ||
|
||
match last { | ||
Some(last) => { | ||
let item = iter.next()?; | ||
last.rotate_left(1); | ||
if let Some(end) = last.last_mut() { | ||
*end = item; | ||
} | ||
Some(last.clone()) | ||
} | ||
None => { | ||
let tmp = array::try_from_fn(|_| iter.next())?; | ||
*last = Some(tmp.clone()); | ||
Some(tmp) | ||
} | ||
} | ||
} | ||
|
||
#[inline] | ||
fn size_hint(&self) -> (usize, Option<usize>) { | ||
let (lower, upper) = self.iter.size_hint(); | ||
// Keep infinite iterator size hint lower bound as `usize::MAX` | ||
if lower == usize::MAX { | ||
(lower, upper) | ||
} else { | ||
(lower.saturating_sub(N - 1), upper.map(|n| n.saturating_sub(N - 1))) | ||
} | ||
} | ||
|
||
#[inline] | ||
fn count(self) -> usize { | ||
self.iter.count().saturating_sub(N - 1) | ||
} | ||
} | ||
|
||
#[unstable(feature = "iter_array_windows", reason = "recently added", issue = "none")] | ||
impl<I, const N: usize> FusedIterator for ArrayWindows<I, N> | ||
where | ||
I: FusedIterator, | ||
I::Item: Clone, | ||
{ | ||
} | ||
|
||
#[unstable(feature = "iter_array_windows", reason = "recently added", issue = "none")] | ||
impl<I, const N: usize> ExactSizeIterator for ArrayWindows<I, N> | ||
where | ||
I: ExactSizeIterator, | ||
I::Item: Clone, | ||
{ | ||
} | ||
|
||
#[unstable(feature = "trusted_len", issue = "37572")] | ||
unsafe impl<I, const N: usize> TrustedLen for ArrayWindows<I, N> | ||
where | ||
I: TrustedLen, | ||
I::Item: Clone, | ||
{ | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -2,12 +2,13 @@ use crate::cmp::{self, Ordering}; | |||||
use crate::ops::{ChangeOutputType, ControlFlow, FromResidual, Residual, Try}; | ||||||
|
||||||
use super::super::TrustedRandomAccessNoCoerce; | ||||||
use super::super::{ | ||||||
ArrayWindows, Inspect, Map, MapWhile, Peekable, Rev, Scan, Skip, SkipWhile, StepBy, Take, | ||||||
TakeWhile, | ||||||
}; | ||||||
use super::super::{Chain, Cloned, Copied, Cycle, Enumerate, Filter, FilterMap, Fuse}; | ||||||
use super::super::{FlatMap, Flatten}; | ||||||
use super::super::{FromIterator, Intersperse, IntersperseWith, Product, Sum, Zip}; | ||||||
use super::super::{ | ||||||
Inspect, Map, MapWhile, Peekable, Rev, Scan, Skip, SkipWhile, StepBy, Take, TakeWhile, | ||||||
}; | ||||||
|
||||||
fn _assert_is_object_safe(_: &dyn Iterator<Item = ()>) {} | ||||||
|
||||||
|
@@ -3057,6 +3058,49 @@ pub trait Iterator { | |||||
Cycle::new(self) | ||||||
} | ||||||
|
||||||
/// Returns an iterator over all contiguous windows of length `N`. The | ||||||
/// windows overlap. If the iterator is shorter than `N`, the iterator | ||||||
/// returns no values. | ||||||
/// | ||||||
/// `array_windows` clones the iterator elements so that they can be part of | ||||||
/// successive windows, this makes this it most suited for iterators of | ||||||
/// references and other values that are cheap to clone. | ||||||
/// | ||||||
/// # Panics | ||||||
/// | ||||||
/// If called with `N = 0`. | ||||||
/// | ||||||
/// # Examples | ||||||
/// | ||||||
/// Basic usage: | ||||||
/// | ||||||
/// ``` | ||||||
/// #![feature(iter_array_windows)] | ||||||
/// | ||||||
/// let mut iter = "rust".chars().array_windows(); | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
I think you missed it? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It's not required because of type inference |
||||||
/// assert_eq!(iter.next(), Some(['r', 'u'])); | ||||||
/// assert_eq!(iter.next(), Some(['u', 's'])); | ||||||
/// assert_eq!(iter.next(), Some(['s', 't'])); | ||||||
/// assert_eq!(iter.next(), None); | ||||||
/// ``` | ||||||
/// | ||||||
/// ``` | ||||||
/// #![feature(iter_array_windows)] | ||||||
/// | ||||||
/// let seq: &[i32] = &[0, 1, 1, 2, 3, 5, 8, 13]; | ||||||
/// for [x, y, z] in seq.iter().copied().array_windows() { | ||||||
/// assert_eq!(x + y, z); | ||||||
/// } | ||||||
/// ``` | ||||||
#[unstable(feature = "iter_array_windows", reason = "recently added", issue = "none")] | ||||||
fn array_windows<const N: usize>(self) -> ArrayWindows<Self, N> | ||||||
where | ||||||
Self: Sized, | ||||||
Self::Item: Clone, | ||||||
{ | ||||||
ArrayWindows::new(self) | ||||||
} | ||||||
|
||||||
/// Sums the elements of an iterator. | ||||||
/// | ||||||
/// Takes each element, adds them together, and returns the result. | ||||||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
use core::iter; | ||
|
||
#[test] | ||
fn test_array_windows_infer() { | ||
let s = [0, 1, 0, 1, 0, 1]; | ||
for [a, b] in s.iter().copied().array_windows() { | ||
assert_eq!(a + b, 1); | ||
} | ||
for [a, b, c, d] in s.iter().copied().array_windows() { | ||
assert_eq!(a + b + c + d, 2); | ||
} | ||
} | ||
|
||
#[test] | ||
fn test_array_windows_size_hint() { | ||
let iter = (0..6).array_windows::<1>(); | ||
assert_eq!(iter.size_hint(), (6, Some(6))); | ||
|
||
let iter = (0..6).array_windows::<3>(); | ||
assert_eq!(iter.size_hint(), (4, Some(4))); | ||
|
||
let iter = (0..6).array_windows::<5>(); | ||
assert_eq!(iter.size_hint(), (2, Some(2))); | ||
|
||
let iter = (0..6).array_windows::<7>(); | ||
assert_eq!(iter.size_hint(), (0, Some(0))); | ||
|
||
let iter = (1..).array_windows::<2>(); | ||
assert_eq!(iter.size_hint(), (usize::MAX, None)); | ||
|
||
let iter = (1..).filter(|x| x % 2 != 0).array_windows::<2>(); | ||
assert_eq!(iter.size_hint(), (0, None)); | ||
} | ||
|
||
#[test] | ||
fn test_array_windows_count() { | ||
let iter = (0..6).array_windows::<1>(); | ||
assert_eq!(iter.count(), 6); | ||
|
||
let iter = (0..6).array_windows::<3>(); | ||
assert_eq!(iter.count(), 4); | ||
|
||
let iter = (0..6).array_windows::<5>(); | ||
assert_eq!(iter.count(), 2); | ||
|
||
let iter = (0..6).array_windows::<7>(); | ||
assert_eq!(iter.count(), 0); | ||
|
||
let iter = (0..6).filter(|x| x % 2 == 0).array_windows::<2>(); | ||
assert_eq!(iter.count(), 2); | ||
|
||
let iter = iter::empty::<i32>().array_windows::<2>(); | ||
assert_eq!(iter.count(), 0); | ||
|
||
let iter = [(); usize::MAX].iter().array_windows::<2>(); | ||
assert_eq!(iter.count(), usize::MAX - 1); | ||
} | ||
|
||
#[test] | ||
fn test_array_windows_nth() { | ||
let mut iter = (0..6).array_windows::<4>(); | ||
assert_eq!(iter.nth(1), Some([1, 2, 3, 4])); | ||
assert_eq!(iter.nth(0), Some([2, 3, 4, 5])); | ||
assert_eq!(iter.nth(1), None); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,4 @@ | ||
mod array_windows; | ||
mod chain; | ||
mod cloned; | ||
mod copied; | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is there some way to assert it in compile time?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
https://blog.rust-lang.org/2021/12/02/Rust-1.57.0.html#panic-in-const-contexts
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It would be ideal but I couldn't get it to work. I tried it for #92393 and get the following error
And if I make the const part of the impl block it doesn't result in a compile time error.