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