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-ptr-addr-of for slice::swap #81160

Merged
merged 1 commit into from
Jan 22, 2021
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions library/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@
#![feature(auto_traits)]
#![feature(or_patterns)]
#![feature(prelude_import)]
#![feature(raw_ref_macros)]
#![feature(repr_simd, platform_intrinsics)]
#![feature(rustc_attrs)]
#![feature(simd_ffi)]
Expand Down
7 changes: 3 additions & 4 deletions library/core/src/slice/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -542,10 +542,9 @@ impl<T> [T] {
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn swap(&mut self, a: usize, b: usize) {
// Can't take two mutable loans from one vector, so instead just cast
// them to their raw pointers to do the swap.
let pa: *mut T = &mut self[a];
let pb: *mut T = &mut self[b];
// Can't take two mutable loans from one vector, so instead use raw pointers.
let pa = ptr::raw_mut!(self[a]);
let pb = ptr::raw_mut!(self[b]);
Copy link
Member

Choose a reason for hiding this comment

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

I'm just curious - the reason that this works, is that we use intrinsic indexing of the slice? If we would go through IndexMut, the problem wouldn't be solved (?)

Copy link
Contributor

Choose a reason for hiding this comment

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

Yes, indexing a slice directly translates to a MIR instruction without any function calls. This is the same as what we do for arithmetic operators for primitive integers. The trait impls only exist for the type system and generics.

// SAFETY: `pa` and `pb` have been created from safe mutable references and refer
// to elements in the slice and therefore are guaranteed to be valid and aligned.
// Note that accessing the elements behind `a` and `b` is checked and will
Expand Down