Skip to content
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
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion library/core/src/array/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -454,7 +454,7 @@ where
///
/// If `iter.next()` panicks, all items already yielded by the iterator are
/// dropped.
fn collect_into_array<I, const N: usize>(iter: &mut I) -> Option<[I::Item; N]>
pub(crate) fn collect_into_array<I, const N: usize>(iter: &mut I) -> Option<[I::Item; N]>
where
I: Iterator,
{
Expand Down
159 changes: 159 additions & 0 deletions library/core/src/iter/adapters/map_windows.rs
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]| {
Comment on lines +29 to +32
Copy link
Contributor

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

// 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);
Copy link
Member

Choose a reason for hiding this comment

The 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()
}
}
4 changes: 4 additions & 0 deletions library/core/src/iter/adapters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ mod inspect;
mod intersperse;
mod map;
mod map_while;
mod map_windows;
mod peekable;
mod rev;
mod scan;
Expand Down Expand Up @@ -48,6 +49,9 @@ pub use self::intersperse::{Intersperse, IntersperseWith};
#[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")]
pub use self::map_while::MapWhile;

#[unstable(feature = "iter_map_windows", reason = "recently added", issue = "87155")]
pub use self::map_windows::MapWindows;

#[unstable(feature = "trusted_random_access", issue = "none")]
pub use self::zip::TrustedRandomAccess;

Expand Down
2 changes: 2 additions & 0 deletions library/core/src/iter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,8 @@ pub use self::adapters::Copied;
pub use self::adapters::Flatten;
#[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")]
pub use self::adapters::MapWhile;
#[unstable(feature = "iter_map_windows", reason = "recently added", issue = "87155")]
pub use self::adapters::MapWindows;
#[unstable(feature = "inplace_iteration", issue = "none")]
pub use self::adapters::SourceIter;
#[stable(feature = "iterator_step_by", since = "1.28.0")]
Expand Down
89 changes: 86 additions & 3 deletions library/core/src/iter/traits/iterator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 = ()>) {}

Expand Down Expand Up @@ -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.
Copy link
Member

Choose a reason for hiding this comment

The 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
Expand Down
Loading