Skip to main content

core/ptr/
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, Clone, PartialEq, Eq)]
15#[repr(transparent)]
16#[ferrocene::prevalidated]
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::ptr::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::ptr::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::ptr::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    // #[unstable(feature = "layout_for_ptr", issue = "69835")]
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` helps this be more clearly the inverse of
177        // `new_unchecked`, letting MIR optimizations fold it away.
178
179        self.as_nonzero().get()
180    }
181
182    /// Returns the alignment as a <code>[NonZero]<[usize]></code>.
183    #[unstable(feature = "ptr_alignment_type", issue = "102070")]
184    #[inline]
185    #[ferrocene::prevalidated]
186    pub const fn as_nonzero(self) -> NonZero<usize> {
187        // This transmutes directly to avoid the UbCheck in `NonZero::new_unchecked`
188        // since there's no way for the user to trip that check anyway -- the
189        // validity invariant of the type would have to have been broken earlier --
190        // and emitting it in an otherwise simple method is bad for compile time.
191
192        // SAFETY: All the discriminants are non-zero.
193        unsafe { mem::transmute::<Alignment, NonZero<usize>>(self) }
194    }
195
196    /// Returns the base-2 logarithm of the alignment.
197    ///
198    /// This is always exact, as `self` represents a power of two.
199    ///
200    /// # Examples
201    ///
202    /// ```
203    /// #![feature(ptr_alignment_type)]
204    /// use std::ptr::Alignment;
205    ///
206    /// assert_eq!(Alignment::of::<u8>().log2(), 0);
207    /// assert_eq!(Alignment::new(1024).unwrap().log2(), 10);
208    /// ```
209    #[unstable(feature = "ptr_alignment_type", issue = "102070")]
210    #[inline]
211    #[ferrocene::prevalidated]
212    pub const fn log2(self) -> u32 {
213        self.as_nonzero().trailing_zeros()
214    }
215
216    /// Returns a bit mask that can be used to match this alignment.
217    ///
218    /// This is equivalent to `!(self.as_usize() - 1)`.
219    ///
220    /// # Examples
221    ///
222    /// ```
223    /// #![feature(ptr_alignment_type)]
224    /// #![feature(ptr_mask)]
225    /// use std::ptr::{Alignment, NonNull};
226    ///
227    /// #[repr(align(1))] struct Align1(u8);
228    /// #[repr(align(2))] struct Align2(u16);
229    /// #[repr(align(4))] struct Align4(u32);
230    /// let one = <NonNull<Align1>>::dangling().as_ptr();
231    /// let two = <NonNull<Align2>>::dangling().as_ptr();
232    /// let four = <NonNull<Align4>>::dangling().as_ptr();
233    ///
234    /// assert_eq!(four.mask(Alignment::of::<Align1>().mask()), four);
235    /// assert_eq!(four.mask(Alignment::of::<Align2>().mask()), four);
236    /// assert_eq!(four.mask(Alignment::of::<Align4>().mask()), four);
237    /// assert_ne!(one.mask(Alignment::of::<Align4>().mask()), one);
238    /// ```
239    #[unstable(feature = "ptr_alignment_type", issue = "102070")]
240    #[inline]
241    pub const fn mask(self) -> usize {
242        // SAFETY: The alignment is always nonzero, and therefore decrementing won't overflow.
243        !(unsafe { self.as_usize().unchecked_sub(1) })
244    }
245
246    // FIXME(const-hack) Remove me once `Ord::max` is usable in const
247    pub(crate) const fn max(a: Self, b: Self) -> Self {
248        if a.as_usize() > b.as_usize() { a } else { b }
249    }
250}
251
252#[unstable(feature = "ptr_alignment_type", issue = "102070")]
253impl fmt::Debug for Alignment {
254    #[ferrocene::prevalidated]
255    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
256        write!(f, "{:?} (1 << {:?})", self.as_nonzero(), self.log2())
257    }
258}
259
260#[unstable(feature = "ptr_alignment_type", issue = "102070")]
261#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
262impl const TryFrom<NonZero<usize>> for Alignment {
263    type Error = num::TryFromIntError;
264
265    #[inline]
266    fn try_from(align: NonZero<usize>) -> Result<Alignment, Self::Error> {
267        align.get().try_into()
268    }
269}
270
271#[unstable(feature = "ptr_alignment_type", issue = "102070")]
272#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
273impl const TryFrom<usize> for Alignment {
274    type Error = num::TryFromIntError;
275
276    #[inline]
277    fn try_from(align: usize) -> Result<Alignment, Self::Error> {
278        Self::new(align).ok_or(num::TryFromIntError(()))
279    }
280}
281
282#[unstable(feature = "ptr_alignment_type", issue = "102070")]
283#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
284impl const From<Alignment> for NonZero<usize> {
285    #[inline]
286    fn from(align: Alignment) -> NonZero<usize> {
287        align.as_nonzero()
288    }
289}
290
291#[unstable(feature = "ptr_alignment_type", issue = "102070")]
292#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
293impl const From<Alignment> for usize {
294    #[inline]
295    fn from(align: Alignment) -> usize {
296        align.as_usize()
297    }
298}
299
300#[unstable(feature = "ptr_alignment_type", issue = "102070")]
301impl cmp::Ord for Alignment {
302    #[inline]
303    fn cmp(&self, other: &Self) -> cmp::Ordering {
304        self.as_nonzero().get().cmp(&other.as_nonzero().get())
305    }
306}
307
308#[unstable(feature = "ptr_alignment_type", issue = "102070")]
309impl cmp::PartialOrd for Alignment {
310    #[inline]
311    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
312        Some(self.cmp(other))
313    }
314}
315
316#[unstable(feature = "ptr_alignment_type", issue = "102070")]
317impl hash::Hash for Alignment {
318    #[inline]
319    #[ferrocene::prevalidated]
320    fn hash<H: hash::Hasher>(&self, state: &mut H) {
321        self.as_nonzero().hash(state)
322    }
323}
324
325/// Returns [`Alignment::MIN`], which is valid for any type.
326#[unstable(feature = "ptr_alignment_type", issue = "102070")]
327#[rustc_const_unstable(feature = "const_default", issue = "143894")]
328impl const Default for Alignment {
329    fn default() -> Alignment {
330        Alignment::MIN
331    }
332}
333
334#[cfg(target_pointer_width = "16")]
335#[derive(Copy, Clone, PartialEq, Eq)]
336#[repr(usize)]
337enum AlignmentEnum {
338    _Align1Shl0 = 1 << 0,
339    _Align1Shl1 = 1 << 1,
340    _Align1Shl2 = 1 << 2,
341    _Align1Shl3 = 1 << 3,
342    _Align1Shl4 = 1 << 4,
343    _Align1Shl5 = 1 << 5,
344    _Align1Shl6 = 1 << 6,
345    _Align1Shl7 = 1 << 7,
346    _Align1Shl8 = 1 << 8,
347    _Align1Shl9 = 1 << 9,
348    _Align1Shl10 = 1 << 10,
349    _Align1Shl11 = 1 << 11,
350    _Align1Shl12 = 1 << 12,
351    _Align1Shl13 = 1 << 13,
352    _Align1Shl14 = 1 << 14,
353    _Align1Shl15 = 1 << 15,
354}
355
356#[cfg(target_pointer_width = "32")]
357#[derive(Copy, Clone, PartialEq, Eq)]
358#[repr(usize)]
359enum AlignmentEnum {
360    _Align1Shl0 = 1 << 0,
361    _Align1Shl1 = 1 << 1,
362    _Align1Shl2 = 1 << 2,
363    _Align1Shl3 = 1 << 3,
364    _Align1Shl4 = 1 << 4,
365    _Align1Shl5 = 1 << 5,
366    _Align1Shl6 = 1 << 6,
367    _Align1Shl7 = 1 << 7,
368    _Align1Shl8 = 1 << 8,
369    _Align1Shl9 = 1 << 9,
370    _Align1Shl10 = 1 << 10,
371    _Align1Shl11 = 1 << 11,
372    _Align1Shl12 = 1 << 12,
373    _Align1Shl13 = 1 << 13,
374    _Align1Shl14 = 1 << 14,
375    _Align1Shl15 = 1 << 15,
376    _Align1Shl16 = 1 << 16,
377    _Align1Shl17 = 1 << 17,
378    _Align1Shl18 = 1 << 18,
379    _Align1Shl19 = 1 << 19,
380    _Align1Shl20 = 1 << 20,
381    _Align1Shl21 = 1 << 21,
382    _Align1Shl22 = 1 << 22,
383    _Align1Shl23 = 1 << 23,
384    _Align1Shl24 = 1 << 24,
385    _Align1Shl25 = 1 << 25,
386    _Align1Shl26 = 1 << 26,
387    _Align1Shl27 = 1 << 27,
388    _Align1Shl28 = 1 << 28,
389    _Align1Shl29 = 1 << 29,
390    _Align1Shl30 = 1 << 30,
391    _Align1Shl31 = 1 << 31,
392}
393
394#[cfg(target_pointer_width = "64")]
395#[derive(Copy, Clone, PartialEq, Eq)]
396#[repr(usize)]
397#[ferrocene::prevalidated]
398enum AlignmentEnum {
399    _Align1Shl0 = 1 << 0,
400    _Align1Shl1 = 1 << 1,
401    _Align1Shl2 = 1 << 2,
402    _Align1Shl3 = 1 << 3,
403    _Align1Shl4 = 1 << 4,
404    _Align1Shl5 = 1 << 5,
405    _Align1Shl6 = 1 << 6,
406    _Align1Shl7 = 1 << 7,
407    _Align1Shl8 = 1 << 8,
408    _Align1Shl9 = 1 << 9,
409    _Align1Shl10 = 1 << 10,
410    _Align1Shl11 = 1 << 11,
411    _Align1Shl12 = 1 << 12,
412    _Align1Shl13 = 1 << 13,
413    _Align1Shl14 = 1 << 14,
414    _Align1Shl15 = 1 << 15,
415    _Align1Shl16 = 1 << 16,
416    _Align1Shl17 = 1 << 17,
417    _Align1Shl18 = 1 << 18,
418    _Align1Shl19 = 1 << 19,
419    _Align1Shl20 = 1 << 20,
420    _Align1Shl21 = 1 << 21,
421    _Align1Shl22 = 1 << 22,
422    _Align1Shl23 = 1 << 23,
423    _Align1Shl24 = 1 << 24,
424    _Align1Shl25 = 1 << 25,
425    _Align1Shl26 = 1 << 26,
426    _Align1Shl27 = 1 << 27,
427    _Align1Shl28 = 1 << 28,
428    _Align1Shl29 = 1 << 29,
429    _Align1Shl30 = 1 << 30,
430    _Align1Shl31 = 1 << 31,
431    _Align1Shl32 = 1 << 32,
432    _Align1Shl33 = 1 << 33,
433    _Align1Shl34 = 1 << 34,
434    _Align1Shl35 = 1 << 35,
435    _Align1Shl36 = 1 << 36,
436    _Align1Shl37 = 1 << 37,
437    _Align1Shl38 = 1 << 38,
438    _Align1Shl39 = 1 << 39,
439    _Align1Shl40 = 1 << 40,
440    _Align1Shl41 = 1 << 41,
441    _Align1Shl42 = 1 << 42,
442    _Align1Shl43 = 1 << 43,
443    _Align1Shl44 = 1 << 44,
444    _Align1Shl45 = 1 << 45,
445    _Align1Shl46 = 1 << 46,
446    _Align1Shl47 = 1 << 47,
447    _Align1Shl48 = 1 << 48,
448    _Align1Shl49 = 1 << 49,
449    _Align1Shl50 = 1 << 50,
450    _Align1Shl51 = 1 << 51,
451    _Align1Shl52 = 1 << 52,
452    _Align1Shl53 = 1 << 53,
453    _Align1Shl54 = 1 << 54,
454    _Align1Shl55 = 1 << 55,
455    _Align1Shl56 = 1 << 56,
456    _Align1Shl57 = 1 << 57,
457    _Align1Shl58 = 1 << 58,
458    _Align1Shl59 = 1 << 59,
459    _Align1Shl60 = 1 << 60,
460    _Align1Shl61 = 1 << 61,
461    _Align1Shl62 = 1 << 62,
462    _Align1Shl63 = 1 << 63,
463}