Skip to main content

core/ptr/
alignment.rs

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