core/ptr/
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#[unstable(feature = "ptr_alignment_type", issue = "102070")]
13#[derive(Copy, Clone, PartialEq, Eq)]
14#[repr(transparent)]
15pub struct Alignment(AlignmentEnum);
16
17// Alignment is `repr(usize)`, but via extra steps.
18const _: () = assert!(size_of::<Alignment>() == size_of::<usize>());
19const _: () = assert!(align_of::<Alignment>() == align_of::<usize>());
20
21fn _alignment_can_be_structurally_matched(a: Alignment) -> bool {
22    matches!(a, Alignment::MIN)
23}
24
25impl Alignment {
26    /// The smallest possible alignment, 1.
27    ///
28    /// All addresses are always aligned at least this much.
29    ///
30    /// # Examples
31    ///
32    /// ```
33    /// #![feature(ptr_alignment_type)]
34    /// use std::ptr::Alignment;
35    ///
36    /// assert_eq!(Alignment::MIN.as_usize(), 1);
37    /// ```
38    #[unstable(feature = "ptr_alignment_type", issue = "102070")]
39    pub const MIN: Self = Self(AlignmentEnum::_Align1Shl0);
40
41    /// Returns the alignment for a type.
42    ///
43    /// This provides the same numerical value as [`align_of`],
44    /// but in an `Alignment` instead of a `usize`.
45    #[unstable(feature = "ptr_alignment_type", issue = "102070")]
46    #[inline]
47    #[must_use]
48    pub const fn of<T>() -> Self {
49        // This can't actually panic since type alignment is always a power of two.
50        const { Alignment::new(align_of::<T>()).unwrap() }
51    }
52
53    /// Creates an `Alignment` from a `usize`, or returns `None` if it's
54    /// not a power of two.
55    ///
56    /// Note that `0` is not a power of two, nor a valid alignment.
57    #[unstable(feature = "ptr_alignment_type", issue = "102070")]
58    #[inline]
59    pub const fn new(align: usize) -> Option<Self> {
60        if align.is_power_of_two() {
61            // SAFETY: Just checked it only has one bit set
62            Some(unsafe { Self::new_unchecked(align) })
63        } else {
64            None
65        }
66    }
67
68    /// Creates an `Alignment` from a power-of-two `usize`.
69    ///
70    /// # Safety
71    ///
72    /// `align` must be a power of two.
73    ///
74    /// Equivalently, it must be `1 << exp` for some `exp` in `0..usize::BITS`.
75    /// It must *not* be zero.
76    #[unstable(feature = "ptr_alignment_type", issue = "102070")]
77    #[inline]
78    #[track_caller]
79    pub const unsafe fn new_unchecked(align: usize) -> Self {
80        assert_unsafe_precondition!(
81            check_language_ub,
82            "Alignment::new_unchecked requires a power of two",
83            (align: usize = align) => align.is_power_of_two()
84        );
85
86        // SAFETY: By precondition, this must be a power of two, and
87        // our variants encompass all possible powers of two.
88        unsafe { mem::transmute::<usize, Alignment>(align) }
89    }
90
91    /// Returns the alignment as a [`usize`].
92    #[unstable(feature = "ptr_alignment_type", issue = "102070")]
93    #[inline]
94    pub const fn as_usize(self) -> usize {
95        self.0 as usize
96    }
97
98    /// Returns the alignment as a <code>[NonZero]<[usize]></code>.
99    #[unstable(feature = "ptr_alignment_type", issue = "102070")]
100    #[inline]
101    pub const fn as_nonzero(self) -> NonZero<usize> {
102        // This transmutes directly to avoid the UbCheck in `NonZero::new_unchecked`
103        // since there's no way for the user to trip that check anyway -- the
104        // validity invariant of the type would have to have been broken earlier --
105        // and emitting it in an otherwise simple method is bad for compile time.
106
107        // SAFETY: All the discriminants are non-zero.
108        unsafe { mem::transmute::<Alignment, NonZero<usize>>(self) }
109    }
110
111    /// Returns the base-2 logarithm of the alignment.
112    ///
113    /// This is always exact, as `self` represents a power of two.
114    ///
115    /// # Examples
116    ///
117    /// ```
118    /// #![feature(ptr_alignment_type)]
119    /// use std::ptr::Alignment;
120    ///
121    /// assert_eq!(Alignment::of::<u8>().log2(), 0);
122    /// assert_eq!(Alignment::new(1024).unwrap().log2(), 10);
123    /// ```
124    #[unstable(feature = "ptr_alignment_type", issue = "102070")]
125    #[inline]
126    pub const fn log2(self) -> u32 {
127        self.as_nonzero().trailing_zeros()
128    }
129
130    /// Returns a bit mask that can be used to match this alignment.
131    ///
132    /// This is equivalent to `!(self.as_usize() - 1)`.
133    ///
134    /// # Examples
135    ///
136    /// ```
137    /// #![feature(ptr_alignment_type)]
138    /// #![feature(ptr_mask)]
139    /// use std::ptr::{Alignment, NonNull};
140    ///
141    /// #[repr(align(1))] struct Align1(u8);
142    /// #[repr(align(2))] struct Align2(u16);
143    /// #[repr(align(4))] struct Align4(u32);
144    /// let one = <NonNull<Align1>>::dangling().as_ptr();
145    /// let two = <NonNull<Align2>>::dangling().as_ptr();
146    /// let four = <NonNull<Align4>>::dangling().as_ptr();
147    ///
148    /// assert_eq!(four.mask(Alignment::of::<Align1>().mask()), four);
149    /// assert_eq!(four.mask(Alignment::of::<Align2>().mask()), four);
150    /// assert_eq!(four.mask(Alignment::of::<Align4>().mask()), four);
151    /// assert_ne!(one.mask(Alignment::of::<Align4>().mask()), one);
152    /// ```
153    #[unstable(feature = "ptr_alignment_type", issue = "102070")]
154    #[inline]
155    pub const fn mask(self) -> usize {
156        // SAFETY: The alignment is always nonzero, and therefore decrementing won't overflow.
157        !(unsafe { self.as_usize().unchecked_sub(1) })
158    }
159
160    // FIXME(const-hack) Remove me once `Ord::max` is usable in const
161    pub(crate) const fn max(a: Self, b: Self) -> Self {
162        if a.as_usize() > b.as_usize() { a } else { b }
163    }
164}
165
166#[unstable(feature = "ptr_alignment_type", issue = "102070")]
167impl fmt::Debug for Alignment {
168    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169        write!(f, "{:?} (1 << {:?})", self.as_nonzero(), self.log2())
170    }
171}
172
173#[unstable(feature = "ptr_alignment_type", issue = "102070")]
174impl TryFrom<NonZero<usize>> for Alignment {
175    type Error = num::TryFromIntError;
176
177    #[inline]
178    fn try_from(align: NonZero<usize>) -> Result<Alignment, Self::Error> {
179        align.get().try_into()
180    }
181}
182
183#[unstable(feature = "ptr_alignment_type", issue = "102070")]
184impl TryFrom<usize> for Alignment {
185    type Error = num::TryFromIntError;
186
187    #[inline]
188    fn try_from(align: usize) -> Result<Alignment, Self::Error> {
189        Self::new(align).ok_or(num::TryFromIntError(()))
190    }
191}
192
193#[unstable(feature = "ptr_alignment_type", issue = "102070")]
194#[rustc_const_unstable(feature = "const_try", issue = "74935")]
195impl const From<Alignment> for NonZero<usize> {
196    #[inline]
197    fn from(align: Alignment) -> NonZero<usize> {
198        align.as_nonzero()
199    }
200}
201
202#[unstable(feature = "ptr_alignment_type", issue = "102070")]
203#[rustc_const_unstable(feature = "const_try", issue = "74935")]
204impl const From<Alignment> for usize {
205    #[inline]
206    fn from(align: Alignment) -> usize {
207        align.as_usize()
208    }
209}
210
211#[unstable(feature = "ptr_alignment_type", issue = "102070")]
212impl cmp::Ord for Alignment {
213    #[inline]
214    fn cmp(&self, other: &Self) -> cmp::Ordering {
215        self.as_nonzero().get().cmp(&other.as_nonzero().get())
216    }
217}
218
219#[unstable(feature = "ptr_alignment_type", issue = "102070")]
220impl cmp::PartialOrd for Alignment {
221    #[inline]
222    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
223        Some(self.cmp(other))
224    }
225}
226
227#[unstable(feature = "ptr_alignment_type", issue = "102070")]
228impl hash::Hash for Alignment {
229    #[inline]
230    fn hash<H: hash::Hasher>(&self, state: &mut H) {
231        self.as_nonzero().hash(state)
232    }
233}
234
235/// Returns [`Alignment::MIN`], which is valid for any type.
236#[unstable(feature = "ptr_alignment_type", issue = "102070")]
237#[rustc_const_unstable(feature = "const_default", issue = "143894")]
238impl const Default for Alignment {
239    fn default() -> Alignment {
240        Alignment::MIN
241    }
242}
243
244#[cfg(target_pointer_width = "16")]
245#[derive(Copy, Clone, PartialEq, Eq)]
246#[repr(usize)]
247enum AlignmentEnum {
248    _Align1Shl0 = 1 << 0,
249    _Align1Shl1 = 1 << 1,
250    _Align1Shl2 = 1 << 2,
251    _Align1Shl3 = 1 << 3,
252    _Align1Shl4 = 1 << 4,
253    _Align1Shl5 = 1 << 5,
254    _Align1Shl6 = 1 << 6,
255    _Align1Shl7 = 1 << 7,
256    _Align1Shl8 = 1 << 8,
257    _Align1Shl9 = 1 << 9,
258    _Align1Shl10 = 1 << 10,
259    _Align1Shl11 = 1 << 11,
260    _Align1Shl12 = 1 << 12,
261    _Align1Shl13 = 1 << 13,
262    _Align1Shl14 = 1 << 14,
263    _Align1Shl15 = 1 << 15,
264}
265
266#[cfg(target_pointer_width = "32")]
267#[derive(Copy, Clone, PartialEq, Eq)]
268#[repr(usize)]
269enum AlignmentEnum {
270    _Align1Shl0 = 1 << 0,
271    _Align1Shl1 = 1 << 1,
272    _Align1Shl2 = 1 << 2,
273    _Align1Shl3 = 1 << 3,
274    _Align1Shl4 = 1 << 4,
275    _Align1Shl5 = 1 << 5,
276    _Align1Shl6 = 1 << 6,
277    _Align1Shl7 = 1 << 7,
278    _Align1Shl8 = 1 << 8,
279    _Align1Shl9 = 1 << 9,
280    _Align1Shl10 = 1 << 10,
281    _Align1Shl11 = 1 << 11,
282    _Align1Shl12 = 1 << 12,
283    _Align1Shl13 = 1 << 13,
284    _Align1Shl14 = 1 << 14,
285    _Align1Shl15 = 1 << 15,
286    _Align1Shl16 = 1 << 16,
287    _Align1Shl17 = 1 << 17,
288    _Align1Shl18 = 1 << 18,
289    _Align1Shl19 = 1 << 19,
290    _Align1Shl20 = 1 << 20,
291    _Align1Shl21 = 1 << 21,
292    _Align1Shl22 = 1 << 22,
293    _Align1Shl23 = 1 << 23,
294    _Align1Shl24 = 1 << 24,
295    _Align1Shl25 = 1 << 25,
296    _Align1Shl26 = 1 << 26,
297    _Align1Shl27 = 1 << 27,
298    _Align1Shl28 = 1 << 28,
299    _Align1Shl29 = 1 << 29,
300    _Align1Shl30 = 1 << 30,
301    _Align1Shl31 = 1 << 31,
302}
303
304#[cfg(target_pointer_width = "64")]
305#[derive(Copy, Clone, PartialEq, Eq)]
306#[repr(usize)]
307enum AlignmentEnum {
308    _Align1Shl0 = 1 << 0,
309    _Align1Shl1 = 1 << 1,
310    _Align1Shl2 = 1 << 2,
311    _Align1Shl3 = 1 << 3,
312    _Align1Shl4 = 1 << 4,
313    _Align1Shl5 = 1 << 5,
314    _Align1Shl6 = 1 << 6,
315    _Align1Shl7 = 1 << 7,
316    _Align1Shl8 = 1 << 8,
317    _Align1Shl9 = 1 << 9,
318    _Align1Shl10 = 1 << 10,
319    _Align1Shl11 = 1 << 11,
320    _Align1Shl12 = 1 << 12,
321    _Align1Shl13 = 1 << 13,
322    _Align1Shl14 = 1 << 14,
323    _Align1Shl15 = 1 << 15,
324    _Align1Shl16 = 1 << 16,
325    _Align1Shl17 = 1 << 17,
326    _Align1Shl18 = 1 << 18,
327    _Align1Shl19 = 1 << 19,
328    _Align1Shl20 = 1 << 20,
329    _Align1Shl21 = 1 << 21,
330    _Align1Shl22 = 1 << 22,
331    _Align1Shl23 = 1 << 23,
332    _Align1Shl24 = 1 << 24,
333    _Align1Shl25 = 1 << 25,
334    _Align1Shl26 = 1 << 26,
335    _Align1Shl27 = 1 << 27,
336    _Align1Shl28 = 1 << 28,
337    _Align1Shl29 = 1 << 29,
338    _Align1Shl30 = 1 << 30,
339    _Align1Shl31 = 1 << 31,
340    _Align1Shl32 = 1 << 32,
341    _Align1Shl33 = 1 << 33,
342    _Align1Shl34 = 1 << 34,
343    _Align1Shl35 = 1 << 35,
344    _Align1Shl36 = 1 << 36,
345    _Align1Shl37 = 1 << 37,
346    _Align1Shl38 = 1 << 38,
347    _Align1Shl39 = 1 << 39,
348    _Align1Shl40 = 1 << 40,
349    _Align1Shl41 = 1 << 41,
350    _Align1Shl42 = 1 << 42,
351    _Align1Shl43 = 1 << 43,
352    _Align1Shl44 = 1 << 44,
353    _Align1Shl45 = 1 << 45,
354    _Align1Shl46 = 1 << 46,
355    _Align1Shl47 = 1 << 47,
356    _Align1Shl48 = 1 << 48,
357    _Align1Shl49 = 1 << 49,
358    _Align1Shl50 = 1 << 50,
359    _Align1Shl51 = 1 << 51,
360    _Align1Shl52 = 1 << 52,
361    _Align1Shl53 = 1 << 53,
362    _Align1Shl54 = 1 << 54,
363    _Align1Shl55 = 1 << 55,
364    _Align1Shl56 = 1 << 56,
365    _Align1Shl57 = 1 << 57,
366    _Align1Shl58 = 1 << 58,
367    _Align1Shl59 = 1 << 59,
368    _Align1Shl60 = 1 << 60,
369    _Align1Shl61 = 1 << 61,
370    _Align1Shl62 = 1 << 62,
371    _Align1Shl63 = 1 << 63,
372}