Skip to main content

gloss_hecs/
alignment.rs

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