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