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    /// This function is identical to [`Alignment::of::<T>()`][Self::of] whenever
63    /// <code>T: [Sized]</code>,
64    /// but also supports determining the alignment required by a `dyn Trait` value, which is the
65    /// alignment of the underlying concrete type.
66    ///
67    /// This provides the same numerical value as [`align_of_val`],
68    /// but in an `Alignment` instead of a `usize`.
69    ///
70    /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
71    ///
72    /// # Examples
73    ///
74    /// ```
75    /// #![feature(ptr_alignment_type)]
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    /// #![feature(ptr_alignment_type)]
89    /// use std::mem::Alignment;
90    ///
91    /// let a: &dyn ToString = &1234u16;
92    /// let b: &dyn ToString = &String::from("abcd");
93    ///
94    /// assert_eq!(Alignment::of_val(a), Alignment::of::<u16>());
95    /// assert_eq!(Alignment::of_val(b), Alignment::of::<String>());
96    /// ```
97    ///
98    /// [type-layout]: ../../reference/type-layout.html#r-layout.primitive
99    #[inline]
100    #[must_use]
101    #[unstable(feature = "ptr_alignment_type", issue = "102070")]
102    pub const fn of_val<T: MetaSized>(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    /// #![feature(ptr_alignment_type)]
146    /// use std::mem::Alignment;
147    ///
148    /// assert_eq!(unsafe { Alignment::of_val_raw(&5i32) }.as_usize(), 4);
149    /// ```
150    ///
151    /// (Caution: [it is not guaranteed][type-layout] that the alignment of `i32` is `4`;
152    /// that is, the above assertion does not pass on all platforms.)
153    ///
154    /// [type-layout]: ../../reference/type-layout.html#r-layout.primitive
155    #[inline]
156    #[must_use]
157    #[unstable(feature = "ptr_alignment_type", issue = "102070")]
158    pub const unsafe fn of_val_raw<T: MetaSized>(val: *const T) -> Self {
159        // SAFETY: precondition propagated to the caller
160        let align = unsafe { mem::align_of_val_raw(val) };
161        // SAFETY: `align_of_val_raw` returns valid alignment
162        unsafe { Alignment::new_unchecked(align) }
163    }
164
165    /// Creates an `Alignment` from a `usize`, or returns `None` if it's
166    /// not a power of two.
167    ///
168    /// Note that `0` is not a power of two, nor a valid alignment.
169    #[unstable(feature = "ptr_alignment_type", issue = "102070")]
170    #[inline]
171    #[ferrocene::prevalidated]
172    pub const fn new(align: usize) -> Option<Self> {
173        if align.is_power_of_two() {
174            // SAFETY: Just checked it only has one bit set
175            Some(unsafe { Self::new_unchecked(align) })
176        } else {
177            None
178        }
179    }
180
181    /// Creates an `Alignment` from a power-of-two `usize`.
182    ///
183    /// # Safety
184    ///
185    /// `align` must be a power of two.
186    ///
187    /// Equivalently, it must be `1 << exp` for some `exp` in `0..usize::BITS`.
188    /// It must *not* be zero.
189    #[unstable(feature = "ptr_alignment_type", issue = "102070")]
190    #[inline]
191    #[track_caller]
192    #[ferrocene::prevalidated]
193    pub const unsafe fn new_unchecked(align: usize) -> Self {
194        assert_unsafe_precondition!(
195            check_language_ub,
196            "Alignment::new_unchecked requires a power of two",
197            (align: usize = align) => align.is_power_of_two()
198        );
199
200        // SAFETY: By precondition, this must be a power of two, and
201        // our variants encompass all possible powers of two.
202        unsafe { mem::transmute::<usize, Alignment>(align) }
203    }
204
205    /// Returns the alignment as a [`usize`].
206    #[unstable(feature = "ptr_alignment_type", issue = "102070")]
207    #[inline]
208    #[ferrocene::prevalidated]
209    pub const fn as_usize(self) -> usize {
210        // Going through `as_nonzero_usize` helps this be more clearly the inverse of
211        // `new_unchecked`, letting MIR optimizations fold it away.
212
213        self.as_nonzero_usize().get()
214    }
215
216    /// Returns the alignment as a <code>[NonZero]<[usize]></code>.
217    #[unstable(feature = "ptr_alignment_type", issue = "102070")]
218    #[deprecated(
219        since = "1.96.0",
220        note = "renamed to `as_nonzero_usize`",
221        suggestion = "as_nonzero_usize"
222    )]
223    #[inline]
224    pub const fn as_nonzero(self) -> NonZero<usize> {
225        self.as_nonzero_usize()
226    }
227
228    /// Returns the alignment as a <code>[NonZero]<[usize]></code>.
229    #[unstable(feature = "ptr_alignment_type", issue = "102070")]
230    #[inline]
231    #[ferrocene::prevalidated]
232    pub const fn as_nonzero_usize(self) -> NonZero<usize> {
233        // This transmutes directly to avoid the UbCheck in `NonZero::new_unchecked`
234        // since there's no way for the user to trip that check anyway -- the
235        // validity invariant of the type would have to have been broken earlier --
236        // and emitting it in an otherwise simple method is bad for compile time.
237
238        // SAFETY: All the discriminants are non-zero.
239        unsafe { mem::transmute::<Alignment, NonZero<usize>>(self) }
240    }
241
242    /// Returns the base-2 logarithm of the alignment.
243    ///
244    /// This is always exact, as `self` represents a power of two.
245    ///
246    /// # Examples
247    ///
248    /// ```
249    /// #![feature(ptr_alignment_type)]
250    /// use std::ptr::Alignment;
251    ///
252    /// assert_eq!(Alignment::of::<u8>().log2(), 0);
253    /// assert_eq!(Alignment::new(1024).unwrap().log2(), 10);
254    /// ```
255    #[unstable(feature = "ptr_alignment_type", issue = "102070")]
256    #[inline]
257    #[ferrocene::prevalidated]
258    pub const fn log2(self) -> u32 {
259        self.as_nonzero_usize().trailing_zeros()
260    }
261
262    /// Returns a bit mask that can be used to match this alignment.
263    ///
264    /// This is equivalent to `!(self.as_usize() - 1)`.
265    ///
266    /// # Examples
267    ///
268    /// ```
269    /// #![feature(ptr_mask)]
270    /// #![feature(ptr_alignment_type)]
271    /// use std::mem::Alignment;
272    /// use std::ptr::NonNull;
273    ///
274    /// #[repr(align(1))] struct Align1(u8);
275    /// #[repr(align(2))] struct Align2(u16);
276    /// #[repr(align(4))] struct Align4(u32);
277    /// let one = <NonNull<Align1>>::dangling().as_ptr();
278    /// let two = <NonNull<Align2>>::dangling().as_ptr();
279    /// let four = <NonNull<Align4>>::dangling().as_ptr();
280    ///
281    /// assert_eq!(four.mask(Alignment::of::<Align1>().mask()), four);
282    /// assert_eq!(four.mask(Alignment::of::<Align2>().mask()), four);
283    /// assert_eq!(four.mask(Alignment::of::<Align4>().mask()), four);
284    /// assert_ne!(one.mask(Alignment::of::<Align4>().mask()), one);
285    /// ```
286    #[unstable(feature = "ptr_alignment_type", issue = "102070")]
287    #[inline]
288    pub const fn mask(self) -> usize {
289        // SAFETY: The alignment is always nonzero, and therefore decrementing won't overflow.
290        !(unsafe { self.as_usize().unchecked_sub(1) })
291    }
292
293    // FIXME(const-hack) Remove me once `Ord::max` is usable in const
294    pub(crate) const fn max(a: Self, b: Self) -> Self {
295        if a.as_usize() > b.as_usize() { a } else { b }
296    }
297}
298
299#[unstable(feature = "ptr_alignment_type", issue = "102070")]
300impl fmt::Debug for Alignment {
301    #[ferrocene::prevalidated]
302    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
303        write!(f, "{:?} (1 << {:?})", self.as_nonzero_usize(), self.log2())
304    }
305}
306
307#[unstable(feature = "ptr_alignment_type", issue = "102070")]
308#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
309const impl TryFrom<NonZero<usize>> for Alignment {
310    type Error = num::TryFromIntError;
311
312    #[inline]
313    fn try_from(align: NonZero<usize>) -> Result<Alignment, Self::Error> {
314        align.get().try_into()
315    }
316}
317
318#[unstable(feature = "ptr_alignment_type", issue = "102070")]
319#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
320const impl TryFrom<usize> for Alignment {
321    type Error = num::TryFromIntError;
322
323    #[inline]
324    fn try_from(align: usize) -> Result<Alignment, Self::Error> {
325        Self::new(align).ok_or(num::TryFromIntError(num::IntErrorKind::NotAPowerOfTwo))
326    }
327}
328
329#[unstable(feature = "ptr_alignment_type", issue = "102070")]
330#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
331const impl From<Alignment> for NonZero<usize> {
332    #[inline]
333    fn from(align: Alignment) -> NonZero<usize> {
334        align.as_nonzero_usize()
335    }
336}
337
338#[unstable(feature = "ptr_alignment_type", issue = "102070")]
339#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
340const impl From<Alignment> for usize {
341    #[inline]
342    fn from(align: Alignment) -> usize {
343        align.as_usize()
344    }
345}
346
347#[unstable(feature = "ptr_alignment_type", issue = "102070")]
348#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
349const impl cmp::Ord for Alignment {
350    #[inline]
351    fn cmp(&self, other: &Self) -> cmp::Ordering {
352        self.as_nonzero_usize().cmp(&other.as_nonzero_usize())
353    }
354}
355
356#[unstable(feature = "ptr_alignment_type", issue = "102070")]
357#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
358const impl cmp::PartialOrd for Alignment {
359    #[inline]
360    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
361        Some(self.cmp(other))
362    }
363}
364
365#[unstable(feature = "ptr_alignment_type", issue = "102070")]
366impl hash::Hash for Alignment {
367    #[inline]
368    #[ferrocene::prevalidated]
369    fn hash<H: hash::Hasher>(&self, state: &mut H) {
370        self.as_nonzero_usize().hash(state)
371    }
372}
373
374/// Returns [`Alignment::MIN`], which is valid for any type.
375#[unstable(feature = "ptr_alignment_type", issue = "102070")]
376#[rustc_const_unstable(feature = "const_default", issue = "143894")]
377const impl Default for Alignment {
378    fn default() -> Alignment {
379        Alignment::MIN
380    }
381}
382
383#[cfg(target_pointer_width = "16")]
384#[derive(Copy)]
385#[derive_const(Clone, PartialEq, Eq)]
386#[repr(usize)]
387#[ferrocene::prevalidated]
388enum AlignmentEnum {
389    _Align1Shl0 = 1 << 0,
390    _Align1Shl1 = 1 << 1,
391    _Align1Shl2 = 1 << 2,
392    _Align1Shl3 = 1 << 3,
393    _Align1Shl4 = 1 << 4,
394    _Align1Shl5 = 1 << 5,
395    _Align1Shl6 = 1 << 6,
396    _Align1Shl7 = 1 << 7,
397    _Align1Shl8 = 1 << 8,
398    _Align1Shl9 = 1 << 9,
399    _Align1Shl10 = 1 << 10,
400    _Align1Shl11 = 1 << 11,
401    _Align1Shl12 = 1 << 12,
402    _Align1Shl13 = 1 << 13,
403    _Align1Shl14 = 1 << 14,
404    _Align1Shl15 = 1 << 15,
405}
406
407#[cfg(target_pointer_width = "32")]
408#[derive(Copy)]
409#[derive_const(Clone, PartialEq, Eq)]
410#[repr(usize)]
411#[ferrocene::prevalidated]
412enum AlignmentEnum {
413    _Align1Shl0 = 1 << 0,
414    _Align1Shl1 = 1 << 1,
415    _Align1Shl2 = 1 << 2,
416    _Align1Shl3 = 1 << 3,
417    _Align1Shl4 = 1 << 4,
418    _Align1Shl5 = 1 << 5,
419    _Align1Shl6 = 1 << 6,
420    _Align1Shl7 = 1 << 7,
421    _Align1Shl8 = 1 << 8,
422    _Align1Shl9 = 1 << 9,
423    _Align1Shl10 = 1 << 10,
424    _Align1Shl11 = 1 << 11,
425    _Align1Shl12 = 1 << 12,
426    _Align1Shl13 = 1 << 13,
427    _Align1Shl14 = 1 << 14,
428    _Align1Shl15 = 1 << 15,
429    _Align1Shl16 = 1 << 16,
430    _Align1Shl17 = 1 << 17,
431    _Align1Shl18 = 1 << 18,
432    _Align1Shl19 = 1 << 19,
433    _Align1Shl20 = 1 << 20,
434    _Align1Shl21 = 1 << 21,
435    _Align1Shl22 = 1 << 22,
436    _Align1Shl23 = 1 << 23,
437    _Align1Shl24 = 1 << 24,
438    _Align1Shl25 = 1 << 25,
439    _Align1Shl26 = 1 << 26,
440    _Align1Shl27 = 1 << 27,
441    _Align1Shl28 = 1 << 28,
442    _Align1Shl29 = 1 << 29,
443    _Align1Shl30 = 1 << 30,
444    _Align1Shl31 = 1 << 31,
445}
446
447#[cfg(target_pointer_width = "64")]
448#[derive(Copy)]
449#[derive_const(Clone, PartialEq, Eq)]
450#[repr(usize)]
451#[ferrocene::prevalidated]
452enum AlignmentEnum {
453    _Align1Shl0 = 1 << 0,
454    _Align1Shl1 = 1 << 1,
455    _Align1Shl2 = 1 << 2,
456    _Align1Shl3 = 1 << 3,
457    _Align1Shl4 = 1 << 4,
458    _Align1Shl5 = 1 << 5,
459    _Align1Shl6 = 1 << 6,
460    _Align1Shl7 = 1 << 7,
461    _Align1Shl8 = 1 << 8,
462    _Align1Shl9 = 1 << 9,
463    _Align1Shl10 = 1 << 10,
464    _Align1Shl11 = 1 << 11,
465    _Align1Shl12 = 1 << 12,
466    _Align1Shl13 = 1 << 13,
467    _Align1Shl14 = 1 << 14,
468    _Align1Shl15 = 1 << 15,
469    _Align1Shl16 = 1 << 16,
470    _Align1Shl17 = 1 << 17,
471    _Align1Shl18 = 1 << 18,
472    _Align1Shl19 = 1 << 19,
473    _Align1Shl20 = 1 << 20,
474    _Align1Shl21 = 1 << 21,
475    _Align1Shl22 = 1 << 22,
476    _Align1Shl23 = 1 << 23,
477    _Align1Shl24 = 1 << 24,
478    _Align1Shl25 = 1 << 25,
479    _Align1Shl26 = 1 << 26,
480    _Align1Shl27 = 1 << 27,
481    _Align1Shl28 = 1 << 28,
482    _Align1Shl29 = 1 << 29,
483    _Align1Shl30 = 1 << 30,
484    _Align1Shl31 = 1 << 31,
485    _Align1Shl32 = 1 << 32,
486    _Align1Shl33 = 1 << 33,
487    _Align1Shl34 = 1 << 34,
488    _Align1Shl35 = 1 << 35,
489    _Align1Shl36 = 1 << 36,
490    _Align1Shl37 = 1 << 37,
491    _Align1Shl38 = 1 << 38,
492    _Align1Shl39 = 1 << 39,
493    _Align1Shl40 = 1 << 40,
494    _Align1Shl41 = 1 << 41,
495    _Align1Shl42 = 1 << 42,
496    _Align1Shl43 = 1 << 43,
497    _Align1Shl44 = 1 << 44,
498    _Align1Shl45 = 1 << 45,
499    _Align1Shl46 = 1 << 46,
500    _Align1Shl47 = 1 << 47,
501    _Align1Shl48 = 1 << 48,
502    _Align1Shl49 = 1 << 49,
503    _Align1Shl50 = 1 << 50,
504    _Align1Shl51 = 1 << 51,
505    _Align1Shl52 = 1 << 52,
506    _Align1Shl53 = 1 << 53,
507    _Align1Shl54 = 1 << 54,
508    _Align1Shl55 = 1 << 55,
509    _Align1Shl56 = 1 << 56,
510    _Align1Shl57 = 1 << 57,
511    _Align1Shl58 = 1 << 58,
512    _Align1Shl59 = 1 << 59,
513    _Align1Shl60 = 1 << 60,
514    _Align1Shl61 = 1 << 61,
515    _Align1Shl62 = 1 << 62,
516    _Align1Shl63 = 1 << 63,
517}