Skip to main content

core/ptr/
alignment.rs

1#![allow(clippy::enum_clike_unportable_variant)]
2
3use crate::marker::MetaSized;
4use crate::num::NonZero;
5use crate::ub_checks::assert_unsafe_precondition;
6use 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, Clone, PartialEq, Eq)]
15#[repr(transparent)]
16pub struct Alignment(AlignmentEnum);
17
18// Alignment is `repr(usize)`, but via extra steps.
19const _: () = assert!(size_of::<Alignment>() == size_of::<usize>());
20const _: () = assert!(align_of::<Alignment>() == align_of::<usize>());
21
22fn _alignment_can_be_structurally_matched(a: Alignment) -> bool {
23    matches!(a, Alignment::MIN)
24}
25
26impl Alignment {
27    /// The smallest possible alignment, 1.
28    ///
29    /// All addresses are always aligned at least this much.
30    ///
31    /// # Examples
32    ///
33    /// ```
34    /// #![feature(ptr_alignment_type)]
35    /// use std::ptr::Alignment;
36    ///
37    /// assert_eq!(Alignment::MIN.as_usize(), 1);
38    /// ```
39    #[unstable(feature = "ptr_alignment_type", issue = "102070")]
40    pub const MIN: Self = Self(AlignmentEnum::_Align1Shl0);
41
42    /// Returns the alignment for a type.
43    ///
44    /// This provides the same numerical value as [`align_of`],
45    /// but in an `Alignment` instead of a `usize`.
46    #[unstable(feature = "ptr_alignment_type", issue = "102070")]
47    #[inline]
48    #[must_use]
49    pub const fn of<T>() -> Self {
50        // This can't actually panic since type alignment is always a power of two.
51        const { Alignment::new(align_of::<T>()).unwrap() }
52    }
53
54    /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
55    ///
56    /// Every reference to a value of the type `T` must be a multiple of this number.
57    ///
58    /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
59    ///
60    /// # Examples
61    ///
62    /// ```
63    /// #![feature(ptr_alignment_type)]
64    /// use std::ptr::Alignment;
65    ///
66    /// assert_eq!(Alignment::of_val(&5i32).as_usize(), 4);
67    /// ```
68    #[inline]
69    #[must_use]
70    #[unstable(feature = "ptr_alignment_type", issue = "102070")]
71    pub const fn of_val<T: MetaSized>(val: &T) -> Self {
72        let align = mem::align_of_val(val);
73        // SAFETY: `align_of_val` returns valid alignment
74        unsafe { Alignment::new_unchecked(align) }
75    }
76
77    /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
78    ///
79    /// Every reference to a value of the type `T` must be a multiple of this number.
80    ///
81    /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
82    ///
83    /// # Safety
84    ///
85    /// This function is only safe to call if the following conditions hold:
86    ///
87    /// - If `T` is `Sized`, this function is always safe to call.
88    /// - If the unsized tail of `T` is:
89    ///     - a [slice], then the length of the slice tail must be an initialized
90    ///       integer, and the size of the *entire value*
91    ///       (dynamic tail length + statically sized prefix) must fit in `isize`.
92    ///       For the special case where the dynamic tail length is 0, this function
93    ///       is safe to call.
94    ///     - a [trait object], then the vtable part of the pointer must point
95    ///       to a valid vtable acquired by an unsizing coercion, and the size
96    ///       of the *entire value* (dynamic tail length + statically sized prefix)
97    ///       must fit in `isize`.
98    ///     - an (unstable) [extern type], then this function is always safe to
99    ///       call, but may panic or otherwise return the wrong value, as the
100    ///       extern type's layout is not known. This is the same behavior as
101    ///       [`Alignment::of_val`] on a reference to a type with an extern type tail.
102    ///     - otherwise, it is conservatively not allowed to call this function.
103    ///
104    /// [trait object]: ../../book/ch17-02-trait-objects.html
105    /// [extern type]: ../../unstable-book/language-features/extern-types.html
106    ///
107    /// # Examples
108    ///
109    /// ```
110    /// #![feature(ptr_alignment_type)]
111    /// #![feature(layout_for_ptr)]
112    /// use std::ptr::Alignment;
113    ///
114    /// assert_eq!(unsafe { Alignment::of_val_raw(&5i32) }.as_usize(), 4);
115    /// ```
116    #[inline]
117    #[must_use]
118    #[unstable(feature = "ptr_alignment_type", issue = "102070")]
119    // #[unstable(feature = "layout_for_ptr", issue = "69835")]
120    pub const unsafe fn of_val_raw<T: MetaSized>(val: *const T) -> Self {
121        // SAFETY: precondition propagated to the caller
122        let align = unsafe { mem::align_of_val_raw(val) };
123        // SAFETY: `align_of_val_raw` returns valid alignment
124        unsafe { Alignment::new_unchecked(align) }
125    }
126
127    /// Creates an `Alignment` from a `usize`, or returns `None` if it's
128    /// not a power of two.
129    ///
130    /// Note that `0` is not a power of two, nor a valid alignment.
131    #[unstable(feature = "ptr_alignment_type", issue = "102070")]
132    #[inline]
133    pub const fn new(align: usize) -> Option<Self> {
134        if align.is_power_of_two() {
135            // SAFETY: Just checked it only has one bit set
136            Some(unsafe { Self::new_unchecked(align) })
137        } else {
138            None
139        }
140    }
141
142    /// Creates an `Alignment` from a power-of-two `usize`.
143    ///
144    /// # Safety
145    ///
146    /// `align` must be a power of two.
147    ///
148    /// Equivalently, it must be `1 << exp` for some `exp` in `0..usize::BITS`.
149    /// It must *not* be zero.
150    #[unstable(feature = "ptr_alignment_type", issue = "102070")]
151    #[inline]
152    #[track_caller]
153    pub const unsafe fn new_unchecked(align: usize) -> Self {
154        assert_unsafe_precondition!(
155            check_language_ub,
156            "Alignment::new_unchecked requires a power of two",
157            (align: usize = align) => align.is_power_of_two()
158        );
159
160        // SAFETY: By precondition, this must be a power of two, and
161        // our variants encompass all possible powers of two.
162        unsafe { mem::transmute::<usize, Alignment>(align) }
163    }
164
165    /// Returns the alignment as a [`usize`].
166    #[unstable(feature = "ptr_alignment_type", issue = "102070")]
167    #[inline]
168    pub const fn as_usize(self) -> usize {
169        self.0 as usize
170    }
171
172    /// Returns the alignment as a <code>[NonZero]<[usize]></code>.
173    #[unstable(feature = "ptr_alignment_type", issue = "102070")]
174    #[inline]
175    pub const fn as_nonzero(self) -> NonZero<usize> {
176        // This transmutes directly to avoid the UbCheck in `NonZero::new_unchecked`
177        // since there's no way for the user to trip that check anyway -- the
178        // validity invariant of the type would have to have been broken earlier --
179        // and emitting it in an otherwise simple method is bad for compile time.
180
181        // SAFETY: All the discriminants are non-zero.
182        unsafe { mem::transmute::<Alignment, NonZero<usize>>(self) }
183    }
184
185    /// Returns the base-2 logarithm of the alignment.
186    ///
187    /// This is always exact, as `self` represents a power of two.
188    ///
189    /// # Examples
190    ///
191    /// ```
192    /// #![feature(ptr_alignment_type)]
193    /// use std::ptr::Alignment;
194    ///
195    /// assert_eq!(Alignment::of::<u8>().log2(), 0);
196    /// assert_eq!(Alignment::new(1024).unwrap().log2(), 10);
197    /// ```
198    #[unstable(feature = "ptr_alignment_type", issue = "102070")]
199    #[inline]
200    pub const fn log2(self) -> u32 {
201        self.as_nonzero().trailing_zeros()
202    }
203
204    /// Returns a bit mask that can be used to match this alignment.
205    ///
206    /// This is equivalent to `!(self.as_usize() - 1)`.
207    ///
208    /// # Examples
209    ///
210    /// ```
211    /// #![feature(ptr_alignment_type)]
212    /// #![feature(ptr_mask)]
213    /// use std::ptr::{Alignment, NonNull};
214    ///
215    /// #[repr(align(1))] struct Align1(u8);
216    /// #[repr(align(2))] struct Align2(u16);
217    /// #[repr(align(4))] struct Align4(u32);
218    /// let one = <NonNull<Align1>>::dangling().as_ptr();
219    /// let two = <NonNull<Align2>>::dangling().as_ptr();
220    /// let four = <NonNull<Align4>>::dangling().as_ptr();
221    ///
222    /// assert_eq!(four.mask(Alignment::of::<Align1>().mask()), four);
223    /// assert_eq!(four.mask(Alignment::of::<Align2>().mask()), four);
224    /// assert_eq!(four.mask(Alignment::of::<Align4>().mask()), four);
225    /// assert_ne!(one.mask(Alignment::of::<Align4>().mask()), one);
226    /// ```
227    #[unstable(feature = "ptr_alignment_type", issue = "102070")]
228    #[inline]
229    pub const fn mask(self) -> usize {
230        // SAFETY: The alignment is always nonzero, and therefore decrementing won't overflow.
231        !(unsafe { self.as_usize().unchecked_sub(1) })
232    }
233
234    // FIXME(const-hack) Remove me once `Ord::max` is usable in const
235    pub(crate) const fn max(a: Self, b: Self) -> Self {
236        if a.as_usize() > b.as_usize() { a } else { b }
237    }
238}
239
240#[unstable(feature = "ptr_alignment_type", issue = "102070")]
241impl fmt::Debug for Alignment {
242    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
243        write!(f, "{:?} (1 << {:?})", self.as_nonzero(), self.log2())
244    }
245}
246
247#[unstable(feature = "ptr_alignment_type", issue = "102070")]
248#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
249impl const TryFrom<NonZero<usize>> for Alignment {
250    type Error = num::TryFromIntError;
251
252    #[inline]
253    fn try_from(align: NonZero<usize>) -> Result<Alignment, Self::Error> {
254        align.get().try_into()
255    }
256}
257
258#[unstable(feature = "ptr_alignment_type", issue = "102070")]
259#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
260impl const TryFrom<usize> for Alignment {
261    type Error = num::TryFromIntError;
262
263    #[inline]
264    fn try_from(align: usize) -> Result<Alignment, Self::Error> {
265        Self::new(align).ok_or(num::TryFromIntError(()))
266    }
267}
268
269#[unstable(feature = "ptr_alignment_type", issue = "102070")]
270#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
271impl const From<Alignment> for NonZero<usize> {
272    #[inline]
273    fn from(align: Alignment) -> NonZero<usize> {
274        align.as_nonzero()
275    }
276}
277
278#[unstable(feature = "ptr_alignment_type", issue = "102070")]
279#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
280impl const From<Alignment> for usize {
281    #[inline]
282    fn from(align: Alignment) -> usize {
283        align.as_usize()
284    }
285}
286
287#[unstable(feature = "ptr_alignment_type", issue = "102070")]
288impl cmp::Ord for Alignment {
289    #[inline]
290    fn cmp(&self, other: &Self) -> cmp::Ordering {
291        self.as_nonzero().get().cmp(&other.as_nonzero().get())
292    }
293}
294
295#[unstable(feature = "ptr_alignment_type", issue = "102070")]
296impl cmp::PartialOrd for Alignment {
297    #[inline]
298    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
299        Some(self.cmp(other))
300    }
301}
302
303#[unstable(feature = "ptr_alignment_type", issue = "102070")]
304impl hash::Hash for Alignment {
305    #[inline]
306    fn hash<H: hash::Hasher>(&self, state: &mut H) {
307        self.as_nonzero().hash(state)
308    }
309}
310
311/// Returns [`Alignment::MIN`], which is valid for any type.
312#[unstable(feature = "ptr_alignment_type", issue = "102070")]
313#[rustc_const_unstable(feature = "const_default", issue = "143894")]
314impl const Default for Alignment {
315    fn default() -> Alignment {
316        Alignment::MIN
317    }
318}
319
320#[cfg(target_pointer_width = "16")]
321#[derive(Copy, Clone, PartialEq, Eq)]
322#[repr(usize)]
323enum AlignmentEnum {
324    _Align1Shl0 = 1 << 0,
325    _Align1Shl1 = 1 << 1,
326    _Align1Shl2 = 1 << 2,
327    _Align1Shl3 = 1 << 3,
328    _Align1Shl4 = 1 << 4,
329    _Align1Shl5 = 1 << 5,
330    _Align1Shl6 = 1 << 6,
331    _Align1Shl7 = 1 << 7,
332    _Align1Shl8 = 1 << 8,
333    _Align1Shl9 = 1 << 9,
334    _Align1Shl10 = 1 << 10,
335    _Align1Shl11 = 1 << 11,
336    _Align1Shl12 = 1 << 12,
337    _Align1Shl13 = 1 << 13,
338    _Align1Shl14 = 1 << 14,
339    _Align1Shl15 = 1 << 15,
340}
341
342#[cfg(target_pointer_width = "32")]
343#[derive(Copy, Clone, PartialEq, Eq)]
344#[repr(usize)]
345enum AlignmentEnum {
346    _Align1Shl0 = 1 << 0,
347    _Align1Shl1 = 1 << 1,
348    _Align1Shl2 = 1 << 2,
349    _Align1Shl3 = 1 << 3,
350    _Align1Shl4 = 1 << 4,
351    _Align1Shl5 = 1 << 5,
352    _Align1Shl6 = 1 << 6,
353    _Align1Shl7 = 1 << 7,
354    _Align1Shl8 = 1 << 8,
355    _Align1Shl9 = 1 << 9,
356    _Align1Shl10 = 1 << 10,
357    _Align1Shl11 = 1 << 11,
358    _Align1Shl12 = 1 << 12,
359    _Align1Shl13 = 1 << 13,
360    _Align1Shl14 = 1 << 14,
361    _Align1Shl15 = 1 << 15,
362    _Align1Shl16 = 1 << 16,
363    _Align1Shl17 = 1 << 17,
364    _Align1Shl18 = 1 << 18,
365    _Align1Shl19 = 1 << 19,
366    _Align1Shl20 = 1 << 20,
367    _Align1Shl21 = 1 << 21,
368    _Align1Shl22 = 1 << 22,
369    _Align1Shl23 = 1 << 23,
370    _Align1Shl24 = 1 << 24,
371    _Align1Shl25 = 1 << 25,
372    _Align1Shl26 = 1 << 26,
373    _Align1Shl27 = 1 << 27,
374    _Align1Shl28 = 1 << 28,
375    _Align1Shl29 = 1 << 29,
376    _Align1Shl30 = 1 << 30,
377    _Align1Shl31 = 1 << 31,
378}
379
380#[cfg(target_pointer_width = "64")]
381#[derive(Copy, Clone, PartialEq, Eq)]
382#[repr(usize)]
383enum AlignmentEnum {
384    _Align1Shl0 = 1 << 0,
385    _Align1Shl1 = 1 << 1,
386    _Align1Shl2 = 1 << 2,
387    _Align1Shl3 = 1 << 3,
388    _Align1Shl4 = 1 << 4,
389    _Align1Shl5 = 1 << 5,
390    _Align1Shl6 = 1 << 6,
391    _Align1Shl7 = 1 << 7,
392    _Align1Shl8 = 1 << 8,
393    _Align1Shl9 = 1 << 9,
394    _Align1Shl10 = 1 << 10,
395    _Align1Shl11 = 1 << 11,
396    _Align1Shl12 = 1 << 12,
397    _Align1Shl13 = 1 << 13,
398    _Align1Shl14 = 1 << 14,
399    _Align1Shl15 = 1 << 15,
400    _Align1Shl16 = 1 << 16,
401    _Align1Shl17 = 1 << 17,
402    _Align1Shl18 = 1 << 18,
403    _Align1Shl19 = 1 << 19,
404    _Align1Shl20 = 1 << 20,
405    _Align1Shl21 = 1 << 21,
406    _Align1Shl22 = 1 << 22,
407    _Align1Shl23 = 1 << 23,
408    _Align1Shl24 = 1 << 24,
409    _Align1Shl25 = 1 << 25,
410    _Align1Shl26 = 1 << 26,
411    _Align1Shl27 = 1 << 27,
412    _Align1Shl28 = 1 << 28,
413    _Align1Shl29 = 1 << 29,
414    _Align1Shl30 = 1 << 30,
415    _Align1Shl31 = 1 << 31,
416    _Align1Shl32 = 1 << 32,
417    _Align1Shl33 = 1 << 33,
418    _Align1Shl34 = 1 << 34,
419    _Align1Shl35 = 1 << 35,
420    _Align1Shl36 = 1 << 36,
421    _Align1Shl37 = 1 << 37,
422    _Align1Shl38 = 1 << 38,
423    _Align1Shl39 = 1 << 39,
424    _Align1Shl40 = 1 << 40,
425    _Align1Shl41 = 1 << 41,
426    _Align1Shl42 = 1 << 42,
427    _Align1Shl43 = 1 << 43,
428    _Align1Shl44 = 1 << 44,
429    _Align1Shl45 = 1 << 45,
430    _Align1Shl46 = 1 << 46,
431    _Align1Shl47 = 1 << 47,
432    _Align1Shl48 = 1 << 48,
433    _Align1Shl49 = 1 << 49,
434    _Align1Shl50 = 1 << 50,
435    _Align1Shl51 = 1 << 51,
436    _Align1Shl52 = 1 << 52,
437    _Align1Shl53 = 1 << 53,
438    _Align1Shl54 = 1 << 54,
439    _Align1Shl55 = 1 << 55,
440    _Align1Shl56 = 1 << 56,
441    _Align1Shl57 = 1 << 57,
442    _Align1Shl58 = 1 << 58,
443    _Align1Shl59 = 1 << 59,
444    _Align1Shl60 = 1 << 60,
445    _Align1Shl61 = 1 << 61,
446    _Align1Shl62 = 1 << 62,
447    _Align1Shl63 = 1 << 63,
448}