Allow the optimizer to elide bounds checks when enumerating IndexSlice/IndecVec.

This commit is contained in:
Jason Newcomb 2025-02-28 09:10:09 -05:00
parent 2f581937e1
commit da0fbc19a5
2 changed files with 10 additions and 0 deletions

View file

@ -65,6 +65,8 @@ impl<I: Idx, T> IndexSlice<I, T> {
#[inline]
pub fn iter_enumerated(&self) -> impl DoubleEndedIterator<Item = (I, &T)> + ExactSizeIterator {
// Allow the optimizer to elide the bounds checking when creating each index.
let _ = I::new(self.len());
self.raw.iter().enumerate().map(|(n, t)| (I::new(n), t))
}
@ -72,6 +74,8 @@ impl<I: Idx, T> IndexSlice<I, T> {
pub fn indices(
&self,
) -> impl DoubleEndedIterator<Item = I> + ExactSizeIterator + Clone + 'static {
// Allow the optimizer to elide the bounds checking when creating each index.
let _ = I::new(self.len());
(0..self.len()).map(|n| I::new(n))
}
@ -84,6 +88,8 @@ impl<I: Idx, T> IndexSlice<I, T> {
pub fn iter_enumerated_mut(
&mut self,
) -> impl DoubleEndedIterator<Item = (I, &mut T)> + ExactSizeIterator {
// Allow the optimizer to elide the bounds checking when creating each index.
let _ = I::new(self.len());
self.raw.iter_mut().enumerate().map(|(n, t)| (I::new(n), t))
}

View file

@ -93,6 +93,8 @@ impl<I: Idx, T> IndexVec<I, T> {
/// be allocated only once, with a capacity of at least `n`.)
#[inline]
pub fn from_fn_n(func: impl FnMut(I) -> T, n: usize) -> Self {
// Allow the optimizer to elide the bounds checking when creating each index.
let _ = I::new(n);
IndexVec::from_raw((0..n).map(I::new).map(func).collect())
}
@ -128,6 +130,8 @@ impl<I: Idx, T> IndexVec<I, T> {
pub fn into_iter_enumerated(
self,
) -> impl DoubleEndedIterator<Item = (I, T)> + ExactSizeIterator {
// Allow the optimizer to elide the bounds checking when creating each index.
let _ = I::new(self.len());
self.raw.into_iter().enumerate().map(|(n, t)| (I::new(n), t))
}