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