-
Notifications
You must be signed in to change notification settings - Fork 12.8k
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::map_windows
#82413
Closed
LukasKalbertodt
wants to merge
3
commits into
rust-lang:master
from
LukasKalbertodt:add-iterator-map-windows
Closed
Add Iterator::map_windows
#82413
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
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,159 @@ | ||
use crate::{ | ||
fmt, | ||
mem::{self, MaybeUninit}, | ||
ptr, | ||
}; | ||
|
||
/// An iterator over the mapped windows of another iterator. | ||
/// | ||
/// This `struct` is created by the [`Iterator::map_windows`]. See its | ||
/// documentation for more information. | ||
#[must_use = "iterators are lazy and do nothing unless consumed"] | ||
#[unstable(feature = "iter_map_windows", reason = "recently added", issue = "87155")] | ||
pub struct MapWindows<I: Iterator, F, const N: usize> { | ||
iter: I, | ||
f: F, | ||
|
||
// The buffer is semantically `[MaybeUninit<I::Item>; 2 * N]`. However, due | ||
// to limitations of const generics, we use this different type. Note that | ||
// it has the same underlying memory layout. | ||
// | ||
// Invariant: if `buffer` is `Some`, `buffer[self.start..self.start + N]` is | ||
// initialized, with all other elements being uninitialized. This also | ||
// implies that `start <= N`. | ||
buffer: Option<[[MaybeUninit<I::Item>; N]; 2]>, | ||
start: usize, | ||
} | ||
|
||
impl<I: Iterator, F, const N: usize> MapWindows<I, F, N> { | ||
pub(in crate::iter) fn new(mut iter: I, f: F) -> Self { | ||
assert!(N > 0, "array in `Iterator::map_windows` must contain more than 0 elements"); | ||
|
||
let buffer = crate::array::collect_into_array(&mut iter).map(|first_half: [_; N]| { | ||
// SAFETY: `MaybeUninit` is `repr(transparent)` and going from `T` to | ||
// `MaybeUninit<T>` is always safe. | ||
let first_half = unsafe { | ||
// FIXME(LukasKalbertodt): use `mem::transmute` once it works with arrays. | ||
let copy: [MaybeUninit<I::Item>; N] = mem::transmute_copy(&first_half); | ||
mem::forget(first_half); | ||
copy | ||
}; | ||
[first_half, MaybeUninit::uninit_array()] | ||
}); | ||
|
||
Self { iter, f, buffer, start: 0 } | ||
} | ||
} | ||
|
||
#[unstable(feature = "iter_map_windows", reason = "recently added", issue = "87155")] | ||
impl<I, F, R, const N: usize> Iterator for MapWindows<I, F, N> | ||
where | ||
I: Iterator, | ||
F: FnMut(&[I::Item; N]) -> R, | ||
{ | ||
type Item = R; | ||
fn next(&mut self) -> Option<Self::Item> { | ||
let buffer_ptr = self.buffer.as_mut()?.as_mut_ptr().cast::<MaybeUninit<I::Item>>(); | ||
|
||
let out = { | ||
debug_assert!(self.start + N <= 2 * N); | ||
|
||
// SAFETY: our invariant guarantees these elements are initialized. | ||
let initialized_part = unsafe { | ||
let ptr = buffer_ptr.add(self.start) as *const [I::Item; N]; | ||
&*ptr | ||
}; | ||
(self.f)(initialized_part) | ||
}; | ||
|
||
// Advance iterator. We first call `next` before changing our buffer at | ||
// all. This means that if `next` panics, our invariant is upheld and | ||
// our `Drop` impl drops the correct elements. | ||
if let Some(next) = self.iter.next() { | ||
if self.start == N { | ||
// We have reached the end of our buffer and have to copy | ||
// everything to the start. Example layout for N = 3. | ||
// | ||
// 0 1 2 3 4 5 0 1 2 3 4 5 | ||
// ┌───┬───┬───┬───┬───┬───┐ ┌───┬───┬───┬───┬───┬───┐ | ||
// │ - │ - │ - │ a │ b │ c │ -> │ b │ c │ n │ - │ - │ - │ | ||
// └───┴───┴───┴───┴───┴───┘ └───┴───┴───┴───┴───┴───┘ | ||
// ↑ ↑ | ||
// start start | ||
|
||
// SAFETY: the two pointers are valid for reads/writes of N -1 | ||
// elements because our array's size is semantically 2 * N. The | ||
// regions also don't overlap for the same reason. | ||
// | ||
// We leave the old elements in place. As soon as `start` is set | ||
// to 0, we treat them as uninitialized and treat their copies | ||
// as initialized. | ||
unsafe { | ||
ptr::copy_nonoverlapping(buffer_ptr.add(N), buffer_ptr, N - 1); | ||
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. The index math on this line seems wrong. Repro: fn main() {
for () in std::iter::repeat("0".to_owned())
.map_windows(|_: &[_; 3]| {})
.take(4) {}
} free(): double free detected in tcache 2
Aborted (core dumped) |
||
(*buffer_ptr.add(N - 1)).write(next); | ||
} | ||
self.start = 0; | ||
|
||
// SAFETY: the index is valid and this is element `a` in the | ||
// diagram above and has not been dropped yet. | ||
unsafe { (*buffer_ptr.add(N)).assume_init_drop() }; | ||
} else { | ||
// SAFETY: `self.start` is < N as guaranteed by the invariant | ||
// plus the check above. Even if the drop at the end panics, | ||
// the invariant is upheld. | ||
// | ||
// Example layout for N = 3: | ||
// | ||
// 0 1 2 3 4 5 0 1 2 3 4 5 | ||
// ┌───┬───┬───┬───┬───┬───┐ ┌───┬───┬───┬───┬───┬───┐ | ||
// │ - │ a │ b │ c │ - │ - │ -> │ - │ - │ b │ c │ n │ - │ | ||
// └───┴───┴───┴───┴───┴───┘ └───┴───┴───┴───┴───┴───┘ | ||
// ↑ ↑ | ||
// start start | ||
// | ||
unsafe { | ||
(*buffer_ptr.add(self.start + N)).write(next); | ||
self.start += 1; | ||
(*buffer_ptr.add(self.start - 1)).assume_init_drop(); | ||
} | ||
} | ||
} else { | ||
// SAFETY: our invariant guarantees that N elements starting from | ||
// `self.start` are initialized. We drop them here. | ||
unsafe { | ||
let initialized_part = crate::ptr::slice_from_raw_parts_mut( | ||
buffer_ptr.add(self.start) as *mut I::Item, | ||
N, | ||
); | ||
crate::ptr::drop_in_place(initialized_part); | ||
} | ||
self.buffer = None; | ||
} | ||
|
||
Some(out) | ||
} | ||
} | ||
|
||
#[unstable(feature = "iter_map_windows", reason = "recently added", issue = "87155")] | ||
impl<I: Iterator, F, const N: usize> Drop for MapWindows<I, F, N> { | ||
fn drop(&mut self) { | ||
if let Some(buffer) = self.buffer.as_mut() { | ||
// SAFETY: our invariant guarantees that N elements starting from | ||
// `self.start` are initialized. We drop them here. | ||
unsafe { | ||
let initialized_part = crate::ptr::slice_from_raw_parts_mut( | ||
buffer.as_mut_ptr().cast::<I::Item>().add(self.start), | ||
N, | ||
); | ||
crate::ptr::drop_in_place(initialized_part); | ||
} | ||
} | ||
} | ||
} | ||
|
||
#[unstable(feature = "iter_map_windows", reason = "recently added", issue = "87155")] | ||
impl<I: Iterator + fmt::Debug, F, const N: usize> fmt::Debug for MapWindows<I, F, N> { | ||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
f.debug_struct("MapWindows").field("iter", &self.iter).finish() | ||
} | ||
} |
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 |
---|---|---|
|
@@ -9,9 +9,8 @@ use super::super::TrustedRandomAccess; | |
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, | ||
}; | ||
use super::super::{Inspect, Map, MapWhile, MapWindows, Peekable, Rev, Scan, Skip, SkipWhile}; | ||
use super::super::{StepBy, Take, TakeWhile}; | ||
|
||
fn _assert_is_object_safe(_: &dyn Iterator<Item = ()>) {} | ||
|
||
|
@@ -1449,6 +1448,90 @@ pub trait Iterator { | |
Flatten::new(self) | ||
} | ||
|
||
/// Calls the given function `f` for each contiguous window of size `N` over | ||
/// `self` and returns an iterator over the outputs of `f`. | ||
/// | ||
/// In the following example, the closure is called three times with the | ||
/// arguments `&['a', 'b']`, `&['b', 'c']` and `&['c', 'd']` respectively. | ||
/// | ||
/// ``` | ||
/// #![feature(iter_map_windows)] | ||
/// | ||
/// let strings = "abcd".chars() | ||
/// .map_windows(|[x, y]| format!("{}+{}", x, y)) | ||
/// .collect::<Vec<String>>(); | ||
/// | ||
/// assert_eq!(strings, vec!["a+b", "b+c", "c+d"]); | ||
/// ``` | ||
/// | ||
/// Note that the const parameter `N` is usually inferred by the | ||
/// destructured argument in the closure. | ||
/// | ||
/// The returned iterator yields 𝑘 − `N` + 1 items (where 𝑘 is the number of | ||
/// items yielded by `self`). If `self` yields fewer than `N` items, the | ||
/// iterator returned from this method is empty. | ||
/// | ||
/// | ||
/// # Panics | ||
/// | ||
/// Panics if `N` is 0. This check will most probably get changed to a | ||
/// compile time error before this method gets stabilized. | ||
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. I've added an item for this to the tracking issue. |
||
/// | ||
/// | ||
/// # Examples | ||
/// | ||
/// Building the sums of neighboring numbers. | ||
/// | ||
/// ``` | ||
/// #![feature(iter_map_windows)] | ||
/// | ||
/// let mut it = [1, 3, 8, 1].iter().map_windows(|&[a, b]| a + b); | ||
/// assert_eq!(it.next(), Some(4)); | ||
/// assert_eq!(it.next(), Some(11)); | ||
/// assert_eq!(it.next(), Some(9)); | ||
/// assert_eq!(it.next(), None); | ||
/// ``` | ||
/// | ||
/// Since the elements in the following example implement `Copy`, we can | ||
/// just copy the array and get an iterator over the windows. | ||
/// | ||
/// ``` | ||
/// #![feature(iter_map_windows)] | ||
/// | ||
/// let mut it = "ferris".chars().map_windows(|w: &[_; 3]| *w); | ||
/// assert_eq!(it.next(), Some(['f', 'e', 'r'])); | ||
/// assert_eq!(it.next(), Some(['e', 'r', 'r'])); | ||
/// assert_eq!(it.next(), Some(['r', 'r', 'i'])); | ||
/// assert_eq!(it.next(), Some(['r', 'i', 's'])); | ||
/// assert_eq!(it.next(), None); | ||
/// ``` | ||
/// | ||
/// You can also use this function to check the sortedness of an iterator. | ||
/// For the simple case, rather use [`Iterator::is_sorted`]. | ||
/// | ||
/// ``` | ||
/// #![feature(iter_map_windows)] | ||
/// | ||
/// let mut it = [0.5, 1.0, 3.5, 3.0, 8.5, 8.5, f32::NAN].iter() | ||
/// .map_windows(|[a, b]| a <= b); | ||
/// | ||
/// assert_eq!(it.next(), Some(true)); // 0.5 <= 1.0 | ||
/// assert_eq!(it.next(), Some(true)); // 1.0 <= 3.5 | ||
/// assert_eq!(it.next(), Some(false)); // 3.5 <= 3.0 | ||
/// assert_eq!(it.next(), Some(true)); // 3.0 <= 8.5 | ||
/// assert_eq!(it.next(), Some(true)); // 8.5 <= 8.5 | ||
/// assert_eq!(it.next(), Some(false)); // 8.5 <= NAN | ||
/// assert_eq!(it.next(), None); | ||
/// ``` | ||
#[unstable(feature = "iter_map_windows", reason = "recently added", issue = "87155")] | ||
fn map_windows<F, R, const N: usize>(self, f: F) -> MapWindows<Self, F, N> | ||
where | ||
Self: Sized, | ||
F: FnMut(&[Self::Item; N]) -> R, | ||
LukasKalbertodt marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
MapWindows::new(self, f) | ||
} | ||
|
||
/// Creates an iterator which ends after the first [`None`]. | ||
/// | ||
/// After an iterator returns [`None`], future calls may or may not yield | ||
|
Oops, something went wrong.
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.
Should this advance the underlying iterator? Normally operations like this are deferred to the first call to
Iterator::next
because iterators should be lazy