Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use raw pointers for .swap(i, j) #903

Merged
merged 1 commit into from
Jan 30, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions src/impl_methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::ptr as std_ptr;
use alloc::slice;
use alloc::vec;
use alloc::vec::Vec;
Expand Down Expand Up @@ -630,11 +629,18 @@ where
S: DataMut,
I: NdIndex<D>,
{
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 {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fwiw, as of Rust 1.46, things like this can be written a little more nicely using Option::zip:

if let Some((offset1, offset2)) = offset1.zip(offset2) {
    unsafe { ... }
} else {
    panic!(...);
}

(or if let Some((offset1, offset2)) = Option::zip(offset1, offset2) if that looks better)

Copy link
Member Author

@bluss bluss Jan 30, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if let (Some(_), Some(_)) = (offset1, offset2) also works IMO. Now which option gives better code :) I wouldn't bother to investigate though.

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`.
Expand All @@ -661,7 +667,7 @@ where
arraytraits::debug_bounds_check(self, &index2);
let off1 = index1.index_unchecked(&self.strides);
let off2 = index2.index_unchecked(&self.strides);
std_ptr::swap(
std::ptr::swap(
self.ptr.as_ptr().offset(off1),
self.ptr.as_ptr().offset(off2),
);
Expand Down