diff --git a/src/impl_methods.rs b/src/impl_methods.rs index 8b1b5a333..a446b75b4 100644 --- a/src/impl_methods.rs +++ b/src/impl_methods.rs @@ -630,11 +630,18 @@ where S: DataMut, I: NdIndex, { - let ptr1: *mut _ = &mut self[index1]; - let ptr2: *mut _ = &mut self[index2]; - unsafe { - std_ptr::swap(ptr1, ptr2); + let ptr = self.as_mut_ptr(); + let offset1 = index1.index_checked(&self.dim, &self.strides); + let offset2 = index2.index_checked(&self.dim, &self.strides); + if let Some(offset1) = offset1 { + if let Some(offset2) = offset2 { + unsafe { + std_ptr::swap(ptr.offset(offset1), ptr.offset(offset2)); + } + return; + } } + panic!("swap: index out of bounds for indices {:?} {:?}", index1, index2); } /// Swap elements *unchecked* at indices `index1` and `index2`.