Skip to main content

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