Skip to content

Implement TrustedRandomAccess for slice::{Chunks, ChunksMut, Windows} #47142

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

Merged
merged 4 commits into from
Jan 5, 2018
Merged
Show file tree
Hide file tree
Changes from 3 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
28 changes: 28 additions & 0 deletions src/libcore/slice/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2117,6 +2117,14 @@ impl<'a, T> ExactSizeIterator for Windows<'a, T> {}
#[unstable(feature = "fused", issue = "35602")]
impl<'a, T> FusedIterator for Windows<'a, T> {}

#[doc(hidden)]
unsafe impl<'a, T> TrustedRandomAccess for Windows<'a, T> {
unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
from_raw_parts(self.v.as_ptr().offset(i as isize), self.size)
}
fn may_have_side_effect() -> bool { false }
}

/// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
/// time).
///
Expand Down Expand Up @@ -2228,6 +2236,16 @@ impl<'a, T> ExactSizeIterator for Chunks<'a, T> {}
#[unstable(feature = "fused", issue = "35602")]
impl<'a, T> FusedIterator for Chunks<'a, T> {}

#[doc(hidden)]
unsafe impl<'a, T> TrustedRandomAccess for Chunks<'a, T> {
unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
let start = i * self.chunk_size;
let end = cmp::min(start + self.chunk_size, self.v.len());
Copy link
Member

@bluss bluss Jan 3, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a potential wraparound here isn't there? i is in bounds but start + size can still wrap around. In particular for [(); !0].chunks((!0)/2 +1) I think.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It turns out Rust ICES on that array. For those that don't like my mobile-friendly syntax, !0 is the same as usize::max_value().

However Rust accepts a vec of this length, and we can demo (playground link)

fn main() {
    let v = vec![(); !0];
    let iter = v.chunks((!0)/2 +1);
    for elt in iter {
        println!("Found chunk of len {}", elt.len());
    }
}

Which has output:

Found chunk of len 9223372036854775808
Found chunk of len 9223372036854775807

from_raw_parts(self.v.as_ptr().offset(start as isize), end - start)
}
fn may_have_side_effect() -> bool { false }
}

/// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
/// elements at a time). When the slice len is not evenly divided by the chunk
/// size, the last slice of the iteration will be the remainder.
Expand Down Expand Up @@ -2331,6 +2349,16 @@ impl<'a, T> ExactSizeIterator for ChunksMut<'a, T> {}
#[unstable(feature = "fused", issue = "35602")]
impl<'a, T> FusedIterator for ChunksMut<'a, T> {}

#[doc(hidden)]
unsafe impl<'a, T> TrustedRandomAccess for ChunksMut<'a, T> {
unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
let start = i * self.chunk_size;
let end = cmp::min(start + self.chunk_size, self.v.len());
from_raw_parts_mut(self.v.as_mut_ptr().offset(start as isize), end - start)
}
fn may_have_side_effect() -> bool { false }
}

//
// Free functions
//
Expand Down
39 changes: 39 additions & 0 deletions src/libcore/tests/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,18 @@ fn test_chunks_last() {
assert_eq!(c2.last().unwrap()[0], 4);
}

#[test]
fn test_chunks_zip() {
let v1: &[i32] = &[0, 1, 2, 3, 4];
let v2: &[i32] = &[6, 7, 8, 9, 10];

let res = v1.chunks(2)
.zip(v2.chunks(2))
.map(|(a, b)| a.iter().sum::<i32>() + b.iter().sum::<i32>())
.collect::<Vec<_>>();
assert_eq!(res, vec![14, 22, 14]);
}

#[test]
fn test_chunks_mut_count() {
let v: &mut [i32] = &mut [0, 1, 2, 3, 4, 5];
Expand Down Expand Up @@ -176,6 +188,20 @@ fn test_chunks_mut_last() {
assert_eq!(c2.last().unwrap()[0], 4);
}

#[test]
fn test_chunks_mut_zip() {
let v1: &mut [i32] = &mut [0, 1, 2, 3, 4];
let v2: &[i32] = &[6, 7, 8, 9, 10];

for (a, b) in v1.chunks_mut(2).zip(v2.chunks(2)) {
let sum = b.iter().sum::<i32>();
for v in a {
*v += sum;
}
}
assert_eq!(v1, [13, 14, 19, 20, 14]);
}

#[test]
fn test_windows_count() {
let v: &[i32] = &[0, 1, 2, 3, 4, 5];
Expand Down Expand Up @@ -215,6 +241,19 @@ fn test_windows_last() {
assert_eq!(c2.last().unwrap()[0], 3);
}

#[test]
fn test_windows_zip() {
let v1: &[i32] = &[0, 1, 2, 3, 4];
let v2: &[i32] = &[6, 7, 8, 9, 10];

let res = v1.windows(2)
.zip(v2.windows(2))
.map(|(a, b)| a.iter().sum::<i32>() + b.iter().sum::<i32>())
.collect::<Vec<_>>();

assert_eq!(res, [14, 18, 22, 26]);
}

#[test]
fn get_range() {
let v: &[i32] = &[0, 1, 2, 3, 4, 5];
Expand Down