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