Skip to content

Commit dc980c4

Browse files
committed
Optimize slice Iter::nth
1 parent d497e43 commit dc980c4

File tree

1 file changed

+8
-10
lines changed

1 file changed

+8
-10
lines changed

library/core/src/slice/iter.rs

+8-10
Original file line numberDiff line numberDiff line change
@@ -1536,17 +1536,15 @@ impl<'a, T> Iterator for Chunks<'a, T> {
15361536
#[inline]
15371537
fn nth(&mut self, n: usize) -> Option<Self::Item> {
15381538
let (start, overflow) = n.overflowing_mul(self.chunk_size);
1539-
if start >= self.v.len() || overflow {
1540-
self.v = &[];
1541-
None
1542-
} else {
1543-
let end = match start.checked_add(self.chunk_size) {
1544-
Some(sum) => cmp::min(self.v.len(), sum),
1545-
None => self.v.len(),
1546-
};
1547-
let nth = &self.v[start..end];
1548-
self.v = &self.v[end..];
1539+
// min(len) makes a wrong start harmless, but enables optimizing this to brachless code
1540+
let chunk_start = &self.v[start.min(self.v.len())..];
1541+
let (nth, remainder) = chunk_start.split_at(self.chunk_size.min(chunk_start.len()));
1542+
if !overflow && start < self.v.len() {
1543+
self.v = remainder;
15491544
Some(nth)
1545+
} else {
1546+
self.v = &self.v[..0]; // cheaper than &[]
1547+
None
15501548
}
15511549
}
15521550

0 commit comments

Comments
 (0)