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