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