Skip to content

Commit f838639

Browse files
authored
Merge pull request #364 from jturner314/add-uswap
Add unchecked swap method (uswap)
2 parents 8ba0479 + dc63098 commit f838639

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

src/impl_methods.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -341,6 +341,24 @@ impl<A, S, D> ArrayBase<S, D> where S: Data<Elem=A>, D: Dimension
341341
}
342342
}
343343

344+
/// Swap elements *unchecked* at indices `index1` and `index2`.
345+
///
346+
/// Indices may be equal.
347+
///
348+
/// **Note:** only unchecked for non-debug builds of ndarray.<br>
349+
/// **Note:** (For `RcArray`) The array must be uniquely held.
350+
pub unsafe fn uswap<I>(&mut self, index1: I, index2: I)
351+
where S: DataMut,
352+
I: NdIndex<D>,
353+
{
354+
debug_assert!(self.data.is_unique());
355+
arraytraits::debug_bounds_check(self, &index1);
356+
arraytraits::debug_bounds_check(self, &index2);
357+
let off1 = index1.index_unchecked(&self.strides);
358+
let off2 = index2.index_unchecked(&self.strides);
359+
std_ptr::swap(self.ptr.offset(off1), self.ptr.offset(off2));
360+
}
361+
344362
// `get` for zero-dimensional arrays
345363
// panics if dimension is not zero. otherwise an element is always present.
346364
fn get_0d(&self) -> &A {

tests/array.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1153,6 +1153,21 @@ fn test_swap() {
11531153
assert_eq!(a, b.t());
11541154
}
11551155

1156+
#[test]
1157+
fn test_uswap() {
1158+
let mut a = arr2(&[[1, 2, 3],
1159+
[4, 5, 6],
1160+
[7, 8, 9]]);
1161+
let b = a.clone();
1162+
1163+
for i in 0..a.rows() {
1164+
for j in i + 1..a.cols() {
1165+
unsafe { a.uswap((i, j), (j, i)) };
1166+
}
1167+
}
1168+
assert_eq!(a, b.t());
1169+
}
1170+
11561171
#[test]
11571172
fn test_shape() {
11581173
let data = [0, 1, 2, 3, 4, 5];

0 commit comments

Comments
 (0)