Struct Alignment

#[repr(transparent)]
pub struct Alignment { pub(in ::mem::alignment) _inner_repr_trick: AlignmentEnum }

A type storing a usize which is a power of two, and thus represents a possible alignment in the Rust abstract machine.

Note that particularly large alignments, while representable in this type, are likely not to be supported by actual allocators and linkers.

Fields

_inner_repr_trick: AlignmentEnum

Implementations

impl Alignment

const MIN: Self = _;

The smallest possible alignment, 1.

All addresses are always aligned at least this much.

Examples

#![feature(ptr_alignment_type)]
use std::mem::Alignment;

assert_eq!(Alignment::MIN.as_usize(), 1);
const fn of<T>() -> Self

Returns the alignment for a type.

This provides the same numerical value as align_of, but in an Alignment instead of a usize.

const fn of_val<T: MetaSized>(val: &T) -> Self

Returns the ABI-required minimum alignment of the type of the value that val points to.

This function is identical to [Alignment::of::<T>()][Self::of] whenever T: [Sized], but also supports determining the alignment required by a dyn Trait value, which is the alignment of the underlying concrete type.

This provides the same numerical value as align_of_val, but in an Alignment instead of a usize.

Examples

#![feature(ptr_alignment_type)]
use std::mem::Alignment;

assert_eq!(Alignment::of_val(&5i32).as_usize(), 4);

(Caution: it is not guaranteed that the alignment of i32 is 4; that is, the above assertion does not pass on all platforms.)

dyn types may have different alignments for different values; Alignment::of_val() can be used to learn those alignments:

#![feature(ptr_alignment_type)]
use std::mem::Alignment;

let a: &dyn ToString = &1234u16;
let b: &dyn ToString = &String::from("abcd");

assert_eq!(Alignment::of_val(a), Alignment::of::<u16>());
assert_eq!(Alignment::of_val(b), Alignment::of::<String>());
const unsafe fn of_val_raw<T: MetaSized>(val: *const T) -> Self

Returns the ABI-required minimum alignment of the type of the value that val points to.

This function is identical to [Alignment::of_val()], except that it can be used with raw pointers in situations where it would be unsound or undesirable to convert them to [& references][primitive@reference] and impose the aliasing rules that come with that.

Safety

This function is safe to call if the pointer is safe to reborrow as &T (in which case you could also call [of_val][Self::of_val]). Otherwise, the following conditions must hold:

  • If T is Sized, this function is always safe to call.
  • If the unsized tail of T is:
    • a [slice], then the length of the slice tail must be an initialized integer, and the size of the entire value (dynamic tail length + statically sized prefix) must fit in isize. For the special case where the dynamic tail length is 0, this function is safe to call.
    • a trait object, then the vtable part of the pointer must point to a valid vtable acquired by an unsizing coercion, and the size of the entire value (dynamic tail length + statically sized prefix) must fit in isize.
    • an (unstable) extern type, then this function is always safe to call, but may panic or otherwise return the wrong value, as the extern type's layout is not known. This is the same behavior as Alignment::of_val on a reference to a type with an extern type tail.
    • otherwise, it is conservatively not allowed to call this function.

Examples

#![feature(ptr_alignment_type)]
use std::mem::Alignment;

assert_eq!(unsafe { Alignment::of_val_raw(&5i32) }.as_usize(), 4);

(Caution: it is not guaranteed that the alignment of i32 is 4; that is, the above assertion does not pass on all platforms.)

const fn new(align: usize) -> Option<Self>

Creates an Alignment from a usize, or returns None if it's not a power of two.

Note that 0 is not a power of two, nor a valid alignment.

const unsafe fn new_unchecked(align: usize) -> Self

Creates an Alignment from a power-of-two usize.

Safety

align must be a power of two.

Equivalently, it must be 1 << exp for some exp in 0..usize::BITS. It must not be zero.

const fn as_usize(self) -> usize

Returns the alignment as a usize.

const fn as_nonzero(self) -> NonZero<usize>

Returns the alignment as a [NonZero]<[usize]>.

const fn as_nonzero_usize(self) -> NonZero<usize>

Returns the alignment as a [NonZero]<[usize]>.

const fn log2(self) -> u32

Returns the base-2 logarithm of the alignment.

This is always exact, as self represents a power of two.

Examples

#![feature(ptr_alignment_type)]
use std::ptr::Alignment;

assert_eq!(Alignment::of::<u8>().log2(), 0);
assert_eq!(Alignment::new(1024).unwrap().log2(), 10);
const fn mask(self) -> usize

Returns a bit mask that can be used to match this alignment.

This is equivalent to !(self.as_usize() - 1).

Examples

#![feature(ptr_mask)]
#![feature(ptr_alignment_type)]
use std::mem::Alignment;
use std::ptr::NonNull;

#[repr(align(1))] struct Align1(u8);
#[repr(align(2))] struct Align2(u16);
#[repr(align(4))] struct Align4(u32);
let one = <NonNull<Align1>>::dangling().as_ptr();
let two = <NonNull<Align2>>::dangling().as_ptr();
let four = <NonNull<Align4>>::dangling().as_ptr();

assert_eq!(four.mask(Alignment::of::<Align1>().mask()), four);
assert_eq!(four.mask(Alignment::of::<Align2>().mask()), four);
assert_eq!(four.mask(Alignment::of::<Align4>().mask()), four);
assert_ne!(one.mask(Alignment::of::<Align4>().mask()), one);
const fn max(a: Self, b: Self) -> Self

Trait Implementations

impl Clone for Alignment

fn clone(&self) -> Alignment

impl Copy for Alignment

impl Debug for Alignment

fn fmt(&self, f: &mut Formatter<'_>) -> Result

impl Default for Alignment

fn default() -> Alignment

impl Eq for Alignment

fn assert_fields_are_eq(&self)

impl Hash for Alignment

fn hash<H: Hasher>(&self, state: &mut H)

impl Ord for Alignment

fn cmp(&self, other: &Self) -> Ordering

impl PartialEq for Alignment

fn eq(&self, other: &Alignment) -> bool

impl PartialOrd for Alignment

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

impl StructuralPartialEq for Alignment

impl TrivialClone for Alignment

impl TryFrom<NonZero<usize>> for Alignment

type Error = TryFromIntError;
fn try_from(align: NonZero<usize>) -> Result<Alignment, Self::Error>

impl TryFrom<usize> for Alignment

type Error = TryFromIntError;
fn try_from(align: usize) -> Result<Alignment, Self::Error>

Auto Trait Implementations

impl Freeze for Alignment

impl RefUnwindSafe for Alignment

impl Send for Alignment

impl Sync for Alignment

impl Unpin for Alignment

impl UnsafeUnpin for Alignment

impl UnwindSafe for Alignment

Blanket Implementations

impl<T> Any for Alignment where T: 'static + ?Sized,

fn type_id(&self) -> TypeId

impl<T> Borrow<T> for Alignment where T: ?Sized,

fn borrow(&self) -> &T

impl<T> BorrowMut<T> for Alignment where T: ?Sized,

fn borrow_mut(&mut self) -> &mut T

impl<T> CloneToUninit for Alignment where T: Clone,

unsafe fn clone_to_uninit(&self, dest: *mut u8)

impl<T> From<T> for Alignment

fn from(t: T) -> T

Returns the argument unchanged.

impl<T> Printable for Alignment where T: Copy + Debug,

impl<T> SizeHint for Alignment where T: ?Sized,

fn lower_bound(&self) -> usize
fn upper_bound(&self) -> Option<usize>

impl<T> SizedTypeProperties for Alignment

impl<T, U> Into<U> for Alignment where U: From<T>,

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of [From]<T> for U chooses to do.

impl<T, U> TryFrom<U> for Alignment where U: Into<T>,

type Error = Infallible;
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

impl<T, U> TryInto<U> for Alignment where U: TryFrom<T>,

type Error = <U as TryFrom<T>>::Error;
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>