alignment.rs - source
Skip to main content core/mem/ alignment.rs 1 #![allow(clippy::enum_clike_unportable_variant)] 2 3 use crate ::marker::MetaSized ; 4 use crate ::num::NonZero ; 5 use crate ::ub_checks::assert_unsafe_precondition ; 6 use crate ::{ cmp , fmt , hash , mem , num }; 7 8 /// A type storing a `usize` which is a power of two, and thus 9 /// represents a possible alignment in the Rust abstract machine. 10 /// 11 /// Note that particularly large alignments, while representable in this type, 12 /// are likely not to be supported by actual allocators and linkers.
13 #[unstable(feature = "ptr_alignment_type" , issue = "102070" )] 14 #[derive( Copy )] 15 #[derive_const( Clone , PartialEq , Eq )] 16 #[repr(transparent)] 17 pub struct Alignment { 18 // This field is never used directly (nor is the enum), 19 // as it's just there to convey the validity invariant. 20 // (Hopefully it'll eventually be a pattern type instead.) 21 _inner_repr_trick: AlignmentEnum , 22 } 23 24 // Alignment is `repr(usize)`, but via extra steps.
25 const _ : () = assert! (size_of::<Alignment>() == size_of::<usize>()); 26 const _ : () = assert! (align_of::<Alignment>() == align_of::<usize>()); 27 28 fn _alignment_can_be_structurally_matched(a: Alignment ) -> bool { 29 matches! (a, Alignment::MIN) 30 } 31 32 impl Alignment { 33 /// The smallest possible alignment, 1. 34 /// 35 /// All addresses are always aligned at least this much. 36 /// 37 /// # Examples 38 /// 39 /// ``` 40 /// #![feature(ptr_alignment_type)] 41 /// use std::mem::Alignment; 42 /// 43 /// assert_eq!(Alignment::MIN.as_usize(), 1); 44 /// ``` 45 #[unstable(feature = "ptr_alignment_type" , issue = "102070" )] 46 pub const MIN: Self = Self :: new ( 1 ). unwrap (); 47 48 /// Returns the alignment for a type.
49 /// 50 /// This provides the same numerical value as [`align_of`], 51 /// but in an `Alignment` instead of a `usize`. 52 #[unstable(feature = "ptr_alignment_type" , issue = "102070" )] 53 #[inline] 54 #[must_use] 55 pub const fn of<T>() -> Self { 56 <T as mem::SizedTypeProperties>:: ALIGNMENT 57 } 58 59 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to. 60 /// 61 /// This function is identical to [`Alignment::of::<T>()`][Self::of] whenever 62 /// <code>T: [Sized]</code>, 63 /// but also supports determining the alignment required by a `dyn Trait` value, which is the 64 /// alignment of the underlying concrete type.
65 /// 66 /// This provides the same numerical value as [`align_of_val`], 67 /// but in an `Alignment` instead of a `usize`. 68 /// 69 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface 70 /// 71 /// # Examples 72 /// 73 /// ``` 74 /// #![feature(ptr_alignment_type)] 75 /// use std::mem::Alignment; 76 /// 77 /// assert_eq!(Alignment::of_val(&5i32).as_usize(), 4); 78 /// ``` 79 /// 80 /// (Caution: [it is not guaranteed][type-layout] that the alignment of `i32` is `4`; 81 /// that is, the above assertion does not pass on all platforms.) 82 /// 83 /// `dyn` types may have different alignments for different values; 84 /// `Alignment::of_val()` can be used to learn those alignments: 85 /// 86 /// ``` 87 /// #![feature(ptr_alignment_type)] 88 /// use std::mem::Alignment; 89 /// 90 /// let a: &dyn ToString = &1234u16; 91 /// let b: &dyn ToString = &String::from("abcd"); 92 /// 93 /// assert_eq!(Alignment::of_val(a), Alignment::of::<u16>()); 94 /// assert_eq!(Alignment::of_val(b), Alignment::of::<String>()); 95 /// ``` 96 /// 97 /// [type-layout]: ../../reference/type-layout.html#r-layout.primitive 98 #[inline] 99 #[must_use] 100 #[unstable(feature = "ptr_alignment_type" , issue = "102070" )] 101 pub const fn of_val<T: MetaSized >(val: & T) -> Self { 102 let align = mem:: align_of_val ( val ); 103 // SAFETY: `align_of_val` returns valid alignment 104 unsafe { Alignment :: new_unchecked ( align ) } 105 } 106 107 /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
108 /// 109 /// This function is identical to [`Alignment::of_val()`], except that it can be used with raw 110 /// pointers in situations where it would be unsound or undesirable to convert them to 111 /// [`&` references][primitive@reference] and impose the aliasing rules that come with that. 112 /// 113 /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface 114 /// 115 /// # Safety 116 /// 117 /// This function is safe to call if the pointer is safe to reborrow as `&T` 118 /// (in which case you could also call [`of_val`][Self::of_val]).
119 /// Otherwise, the following conditions must hold: 120 /// 121 /// - If `T` is `Sized`, this function is always safe to call. 122 /// - If the unsized tail of `T` is: 123 /// - a [slice], then the length of the slice tail must be an initialized 124 /// integer, and the size of the *entire value* 125 /// (dynamic tail length + statically sized prefix) must fit in `isize`. 126 /// For the special case where the dynamic tail length is 0, this function 127 /// is safe to call.
128 /// - a [trait object], then the vtable part of the pointer must point 129 /// to a valid vtable acquired by an unsizing coercion, and the size 130 /// of the *entire value* (dynamic tail length + statically sized prefix) 131 /// must fit in `isize`. 132 /// - an (unstable) [extern type], then this function is always safe to 133 /// call, but may panic or otherwise return the wrong value, as the 134 /// extern type's layout is not known.
This is the same behavior as 135 /// [`Alignment::of_val`] on a reference to a type with an extern type tail. 136 /// - otherwise, it is conservatively not allowed to call this function. 137 /// 138 /// [trait object]: ../../book/ch17-02-trait-objects.html 139 /// [extern type]: ../../unstable-book/language-features/extern-types.html 140 /// 141 /// # Examples 142 /// 143 /// ``` 144 /// #![feature(ptr_alignment_type)] 145 /// use std::mem::Alignment; 146 /// 147 /// assert_eq!(unsafe { Alignment::of_val_raw(&5i32) }.as_usize(), 4); 148 /// ``` 149 /// 150 /// (Caution: [it is not guaranteed][type-layout] that the alignment of `i32` is `4`; 151 /// that is, the above assertion does not pass on all platforms.) 152 /// 153 /// [type-layout]: ../../reference/type-layout.html#r-layout.primitive 154 #[inline] 155 #[must_use] 156 #[unstable(feature = "ptr_alignment_type" , issue = "102070" )] 157 pub const unsafe fn of_val_raw<T: MetaSized >(val: *const T) -> Self { 158 // SAFETY: precondition propagated to the caller 159 let align = unsafe { mem:: align_of_val_raw ( val ) }; 160 // SAFETY: `align_of_val_raw` returns valid alignment 161 unsafe { Alignment :: new_unchecked ( align ) } 162 } 163 164 /// Creates an `Alignment` from a `usize`, or returns `None` if it's 165 /// not a power of two.
166 /// 167 /// Note that `0` is not a power of two, nor a valid alignment. 168 #[unstable(feature = "ptr_alignment_type" , issue = "102070" )] 169 #[inline] 170 pub const fn new(align: usize ) -> Option < Self > { 171 if align . is_power_of_two () { 172 // SAFETY: Just checked it only has one bit set 173 Some ( unsafe { Self :: new_unchecked ( align ) }) 174 } else { 175 None 176 } 177 } 178 179 /// Creates an `Alignment` from a power-of-two `usize`.
180 /// 181 /// # Safety 182 /// 183 /// `align` must be a power of two. 184 /// 185 /// Equivalently, it must be `1 << exp` for some `exp` in `0..usize::BITS`. 186 /// It must *not* be zero. 187 #[unstable(feature = "ptr_alignment_type" , issue = "102070" )] 188 #[inline] 189 #[track_caller] 190 pub const unsafe fn new_unchecked(align: usize ) -> Self { 191 assert_unsafe_precondition! ( 192 check_language_ub, 193 "Alignment::new_unchecked requires a power of two" , 194 (align: usize = align) => align.is_power_of_two() 195 ); 196 197 // SAFETY: By precondition, this must be a power of two, and 198 // our variants encompass all possible powers of two.
199 unsafe { mem:: transmute ::< usize , Alignment >( align ) } 200 } 201 202 /// Returns the alignment as a [`u
The rest of this page is on the live site.