Skip to content

Commit a4ee9c6

Browse files
committed
core: Use primitive indexing in slice's Index/IndexMut
[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][..])
1 parent a5dbf8a commit a4ee9c6

File tree

2 files changed

+5
-5
lines changed

2 files changed

+5
-5
lines changed

src/libcore/slice.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -520,8 +520,8 @@ impl<T> ops::Index<usize> for [T] {
520520
type Output = T;
521521

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

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

src/test/run-fail/bounds-check-no-overflow.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
// option. This file may not be copied, modified, or distributed
99
// except according to those terms.
1010

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

1313
use std::usize;
1414
use std::mem::size_of;

0 commit comments

Comments
 (0)