diff options
| author | Ibraheem Ahmed <ibrah1440@gmail.com> | 2021-10-11 16:12:43 -0400 |
|---|---|---|
| committer | Ibraheem Ahmed <ibrah1440@gmail.com> | 2021-10-11 16:14:31 -0400 |
| commit | 2a8ff8df54d5effdfd0154009eea2d50bdd5e598 (patch) | |
| tree | 71471acbb71e59d12b9e3cd62762355d113b0ea1 | |
| parent | 33ecc33268c1cda372c90c203cead2721a822363 (diff) | |
| download | rust-2a8ff8df54d5effdfd0154009eea2d50bdd5e598.tar.gz rust-2a8ff8df54d5effdfd0154009eea2d50bdd5e598.zip | |
improve slice::swap panic message
| -rw-r--r-- | library/core/src/slice/mod.rs | 19 |
1 files changed, 15 insertions, 4 deletions
diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs index 496cc359c19..8108d52071b 100644 --- a/library/core/src/slice/mod.rs +++ b/library/core/src/slice/mod.rs @@ -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) } } @@ -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 { @@ -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]); } |
