Skip to content

Commit d8843d9

Browse files
authoredJan 16, 2021
Rollup merge of #80670 - the8472:fix-zip-trusted-random-access-composition, r=m-ou-se
TrustedRandomAaccess specialization composes incorrectly for nested iter::Zips I found this while working on improvements for TRA. After partially consuming a Zip adapter and then wrapping it into another Zip where the adapters use their `TrustedRandomAccess` specializations leads to the outer adapter returning elements which should have already been consumed. If the optimizer gets tripped up by the addition this might affect performance for chained `zip()` iterators even when the inner one is not partially advanced but it would require more extensive fixes to `TrustedRandomAccess` to communicate those offsets earlier. Included test fails on nightly, [playground link](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=24fa1edf8a104ff31f5a24830593b01f)
2 parents af5b0d9 + af2983a commit d8843d9

File tree

3 files changed

+23
-0
lines changed

3 files changed

+23
-0
lines changed
 

‎library/core/src/iter/adapters/zip.rs

+1
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,7 @@ where
286286

287287
#[inline]
288288
unsafe fn get_unchecked(&mut self, idx: usize) -> <Self as Iterator>::Item {
289+
let idx = self.index + idx;
289290
// SAFETY: the caller must uphold the contract for
290291
// `Iterator::__iterator_get_unchecked`.
291292
unsafe { (self.a.__iterator_get_unchecked(idx), self.b.__iterator_get_unchecked(idx)) }

‎library/core/tests/iter.rs

+21
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
use core::cell::Cell;
44
use core::convert::TryFrom;
5+
use core::iter::TrustedRandomAccess;
56
use core::iter::*;
67

78
/// An iterator wrapper that panics whenever `next` or `next_back` is called
@@ -601,6 +602,26 @@ fn test_zip_nth_back_side_effects_exhausted() {
601602
assert_eq!(b, vec![200, 300, 400]);
602603
}
603604

605+
#[test]
606+
fn test_zip_trusted_random_access_composition() {
607+
let a = [0, 1, 2, 3, 4];
608+
let b = a;
609+
let c = a;
610+
611+
let a = a.iter().copied();
612+
let b = b.iter().copied();
613+
let mut c = c.iter().copied();
614+
c.next();
615+
616+
let mut z1 = a.zip(b);
617+
assert_eq!(z1.next().unwrap(), (0, 0));
618+
619+
let mut z2 = z1.zip(c);
620+
fn assert_trusted_random_access<T: TrustedRandomAccess>(_a: &T) {}
621+
assert_trusted_random_access(&z2);
622+
assert_eq!(z2.next().unwrap(), ((1, 1), 1));
623+
}
624+
604625
#[test]
605626
fn test_iterator_step_by() {
606627
// Identity

‎library/core/tests/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@
7575
#![feature(const_option)]
7676
#![feature(integer_atomics)]
7777
#![feature(slice_group_by)]
78+
#![feature(trusted_random_access)]
7879
#![deny(unsafe_op_in_unsafe_fn)]
7980

8081
extern crate test;

0 commit comments

Comments
 (0)
Please sign in to comment.