Skip to main content

core/mem/
alignment.rs

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