Skip to content

Commit

Permalink
Mark <*const _>::align_offset and <*mut _>::align_offset as `cons…
Browse files Browse the repository at this point in the history
…t fn`
  • Loading branch information
WaffleLapkin committed Nov 16, 2021
1 parent d914f17 commit 8f5f094
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 6 deletions.
21 changes: 18 additions & 3 deletions library/core/src/ptr/const_ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -879,15 +879,30 @@ impl<T: ?Sized> *const T {
/// # } }
/// ```
#[stable(feature = "align_offset", since = "1.36.0")]
pub fn align_offset(self, align: usize) -> usize
#[rustc_const_unstable(feature = "const_align_offset", issue = "none")]
pub const fn align_offset(self, align: usize) -> usize
where
T: Sized,
{
if !align.is_power_of_two() {
panic!("align_offset: align is not a power-of-two");
}
// SAFETY: `align` has been checked to be a power of 2 above
unsafe { align_offset(self, align) }

fn rt_impl<T>(p: *const T, align: usize) -> usize {
// SAFETY: `align` has been checked to be a power of 2 above
unsafe { align_offset(p, align) }
}

const fn ctfe_impl<T>(_: *const T, _: usize) -> usize {
usize::MAX
}

// SAFETY:
// It is permisseble for `align_offset` to always return `usize::MAX`,
// algorithm correctness can not depend on `align_offset` returning non-max values.
//
// As such the behaviour can't change after replacing `align_offset` with `usize::MAX`, only performance can.
unsafe { intrinsics::const_eval_select((self, align), ctfe_impl, rt_impl) }
}
}

Expand Down
21 changes: 18 additions & 3 deletions library/core/src/ptr/mut_ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1142,15 +1142,30 @@ impl<T: ?Sized> *mut T {
/// # } }
/// ```
#[stable(feature = "align_offset", since = "1.36.0")]
pub fn align_offset(self, align: usize) -> usize
#[rustc_const_unstable(feature = "const_align_offset", issue = "none")]
pub const fn align_offset(self, align: usize) -> usize
where
T: Sized,
{
if !align.is_power_of_two() {
panic!("align_offset: align is not a power-of-two");
}
// SAFETY: `align` has been checked to be a power of 2 above
unsafe { align_offset(self, align) }

fn rt_impl<T>(p: *mut T, align: usize) -> usize {
// SAFETY: `align` has been checked to be a power of 2 above
unsafe { align_offset(p, align) }
}

const fn ctfe_impl<T>(_: *mut T, _: usize) -> usize {
usize::MAX
}

// SAFETY:
// It is permisseble for `align_offset` to always return `usize::MAX`,
// algorithm correctness can not depend on `align_offset` returning non-max values.
//
// As such the behaviour can't change after replacing `align_offset` with `usize::MAX`, only performance can.
unsafe { intrinsics::const_eval_select((self, align), ctfe_impl, rt_impl) }
}
}

Expand Down

0 comments on commit 8f5f094

Please sign in to comment.