Skip to content

Commit

Permalink
core: Use primitive indexing in slice's Index/IndexMut
Browse files Browse the repository at this point in the history
[T]'s Index implementation is normally not used for indexing, instead
the compiler supplied indexing is used.

Use the compiler supplied version in Index/IndexMut.

This removes an inconsistency:

Compiler supplied bound check failures look like this:

thread 'main' panicked at 'index out of bounds: the len is 3 but the index is 4'

If you convince Rust to use the Index impl for slices, bounds check
failure looks like this instead:

thread 'main' panicked at 'assertion failed: index < self.len()'

The latter is used if you for example use Index generically::

   use std::ops::Index;
   fn foo<T: ?Sized>(x: &T) where T: Index<usize> { &x[4]; }

   foo(&[1, 2, 3][..])
  • Loading branch information
bluss committed Sep 14, 2016
1 parent a5dbf8a commit a4ee9c6
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 5 deletions.
8 changes: 4 additions & 4 deletions src/libcore/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -520,8 +520,8 @@ impl<T> ops::Index<usize> for [T] {
type Output = T;

fn index(&self, index: usize) -> &T {
assert!(index < self.len());
unsafe { self.get_unchecked(index) }
// NB built-in indexing
&(*self)[index]
}
}

Expand All @@ -530,8 +530,8 @@ impl<T> ops::Index<usize> for [T] {
impl<T> ops::IndexMut<usize> for [T] {
#[inline]
fn index_mut(&mut self, index: usize) -> &mut T {
assert!(index < self.len());
unsafe { self.get_unchecked_mut(index) }
// NB built-in indexing
&mut (*self)[index]
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/test/run-fail/bounds-check-no-overflow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// error-pattern:assertion failed: index < self.len()
// error-pattern:index out of bounds

use std::usize;
use std::mem::size_of;
Expand Down

0 comments on commit a4ee9c6

Please sign in to comment.