summaryrefslogtreecommitdiffstats
path: root/library/core/src/mem/valid_align.rs
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--library/core/src/mem/valid_align.rs18
1 files changed, 16 insertions, 2 deletions
diff --git a/library/core/src/mem/valid_align.rs b/library/core/src/mem/valid_align.rs
index fcfa95120..32b2afb72 100644
--- a/library/core/src/mem/valid_align.rs
+++ b/library/core/src/mem/valid_align.rs
@@ -1,4 +1,5 @@
use crate::convert::TryFrom;
+use crate::intrinsics::assert_unsafe_precondition;
use crate::num::NonZeroUsize;
use crate::{cmp, fmt, hash, mem, num};
@@ -26,7 +27,8 @@ impl ValidAlign {
/// It must *not* be zero.
#[inline]
pub(crate) const unsafe fn new_unchecked(align: usize) -> Self {
- debug_assert!(align.is_power_of_two());
+ // SAFETY: Precondition passed to the caller.
+ unsafe { assert_unsafe_precondition!((align: usize) => align.is_power_of_two()) };
// SAFETY: By precondition, this must be a power of two, and
// our variants encompass all possible powers of two.
@@ -34,9 +36,14 @@ impl ValidAlign {
}
#[inline]
+ pub(crate) const fn as_usize(self) -> usize {
+ self.0 as usize
+ }
+
+ #[inline]
pub(crate) const fn as_nonzero(self) -> NonZeroUsize {
// SAFETY: All the discriminants are non-zero.
- unsafe { NonZeroUsize::new_unchecked(self.0 as usize) }
+ unsafe { NonZeroUsize::new_unchecked(self.as_usize()) }
}
/// Returns the base 2 logarithm of the alignment.
@@ -46,6 +53,13 @@ impl ValidAlign {
pub(crate) fn log2(self) -> u32 {
self.as_nonzero().trailing_zeros()
}
+
+ /// Returns the alignment for a type.
+ #[inline]
+ pub(crate) fn of<T>() -> Self {
+ // SAFETY: rustc ensures that type alignment is always a power of two.
+ unsafe { ValidAlign::new_unchecked(mem::align_of::<T>()) }
+ }
}
impl fmt::Debug for ValidAlign {