Skip to content

Commit

Permalink
std: use ptr.offset where possible in the vec iterator.
Browse files Browse the repository at this point in the history
  • Loading branch information
huonw authored and thestinger committed Aug 3, 2013
1 parent 54e685d commit fbb7cd3
Showing 1 changed file with 38 additions and 8 deletions.
46 changes: 38 additions & 8 deletions src/libstd/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2141,11 +2141,15 @@ macro_rules! iterator {
None
} else {
let old = self.ptr;
// purposefully don't use 'ptr.offset' because for
// vectors with 0-size elements this would return the
// same pointer.
self.ptr = cast::transmute(self.ptr as uint +
sys::nonzero_size_of::<T>());
self.ptr = if sys::size_of::<T>() == 0 {
// purposefully don't use 'ptr.offset' because for
// vectors with 0-size elements this would return the
// same pointer.
cast::transmute(self.ptr as uint + 1)
} else {
self.ptr.offset(1)
};

Some(cast::transmute(old))
}
}
Expand All @@ -2171,9 +2175,12 @@ macro_rules! double_ended_iterator {
if self.end == self.ptr {
None
} else {
// See above for why 'ptr.offset' isn't used
self.end = cast::transmute(self.end as uint -
sys::nonzero_size_of::<T>());
self.end = if sys::size_of::<T>() == 0 {
// See above for why 'ptr.offset' isn't used
cast::transmute(self.end as uint - 1)
} else {
self.end.offset(-1)
};
Some(cast::transmute(self.end))
}
}
Expand Down Expand Up @@ -3566,3 +3573,26 @@ mod tests {
assert!(cnt == 3);
}
}

#[cfg(test)]
mod bench {
use extra::test::BenchHarness;
use vec;
use option::*;

#[bench]
fn iterator(bh: &mut BenchHarness) {
// peculiar numbers to stop LLVM from optimising the summation
// out.
let v = vec::from_fn(100, |i| i ^ (i << 1) ^ (i >> 1));

do bh.iter {
let mut sum = 0;
foreach x in v.iter() {
sum += *x;
}
// sum == 11806, to stop dead code elimination.
if sum == 0 {fail!()}
}
}
}

0 comments on commit fbb7cd3

Please sign in to comment.