Skip to content

Commit

Permalink
improve slice::swap panic message
Browse files Browse the repository at this point in the history
  • Loading branch information
ibraheemdev committed Oct 11, 2021
1 parent 33ecc33 commit 2a8ff8d
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions library/core/src/slice/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -560,8 +560,9 @@ impl<T> [T] {
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn swap(&mut self, a: usize, b: usize) {
assert!(a < self.len());
assert!(b < self.len());
assert_in_bounds(self.len(), a);
assert_in_bounds(self.len(), b);

// SAFETY: we just checked that both `a` and `b` are in bounds
unsafe { self.swap_unchecked(a, b) }
}
Expand Down Expand Up @@ -595,8 +596,12 @@ impl<T> [T] {
/// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
#[unstable(feature = "slice_swap_unchecked", issue = "88539")]
pub unsafe fn swap_unchecked(&mut self, a: usize, b: usize) {
debug_assert!(a < self.len());
debug_assert!(b < self.len());
#[cfg(debug_assertions)]
{
assert_in_bounds(self.len(), a);
assert_in_bounds(self.len(), b);
}

let ptr = self.as_mut_ptr();
// SAFETY: caller has to guarantee that `a < self.len()` and `b < self.len()`
unsafe {
Expand Down Expand Up @@ -3497,6 +3502,12 @@ impl<T> [T] {
}
}

fn assert_in_bounds(len: usize, idx: usize) {
if idx >= len {
panic!("index out of bounds: the len is {} but the index is {}", len, idx);
}
}

trait CloneFromSpec<T> {
fn spec_clone_from(&mut self, src: &[T]);
}
Expand Down

0 comments on commit 2a8ff8d

Please sign in to comment.