From 5c873be9c323f15f102720fe9085e2c4e982bb6d Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Sun, 22 Nov 2015 18:44:37 +0530 Subject: [PATCH] Improve slice indexing assertion --- src/libcore/slice.rs | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/src/libcore/slice.rs b/src/libcore/slice.rs index efb782fece8..890ca43580b 100644 --- a/src/libcore/slice.rs +++ b/src/libcore/slice.rs @@ -566,14 +566,29 @@ impl ops::IndexMut for [T] { } } +#[inline(never)] +#[cold] +fn slice_index_len_fail(index: usize, len: usize) -> ! { + panic!("index {} out of range for slice of length {}", index, len); +} + +#[inline(never)] +#[cold] +fn slice_index_order_fail(index: usize, end: usize) -> ! { + panic!("slice index starts at {} but ends at {}", index, end); +} + #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index> for [T] { type Output = [T]; #[inline] fn index(&self, index: ops::Range) -> &[T] { - assert!(index.start <= index.end); - assert!(index.end <= self.len()); + if index.start > index.end { + slice_index_order_fail(index.start, index.end); + } else if index.end > self.len() { + slice_index_len_fail(index.end, self.len()); + } unsafe { from_raw_parts ( self.as_ptr().offset(index.start as isize), @@ -614,8 +629,11 @@ impl ops::Index for [T] { impl ops::IndexMut> for [T] { #[inline] fn index_mut(&mut self, index: ops::Range) -> &mut [T] { - assert!(index.start <= index.end); - assert!(index.end <= self.len()); + if index.start > index.end { + slice_index_order_fail(index.start, index.end); + } else if index.end > self.len() { + slice_index_len_fail(index.end, self.len()); + } unsafe { from_raw_parts_mut( self.as_mut_ptr().offset(index.start as isize),