enum_table/
intrinsics.rs

1#[inline(always)]
2pub(crate) const fn cast_variant<T>(u: &usize) -> &T {
3    #[cfg(target_endian = "big")]
4    unsafe {
5        &*(u as *const usize)
6            .cast::<u8>()
7            .add(core::mem::size_of::<usize>() - core::mem::size_of::<T>())
8            .cast::<T>()
9    }
10    #[cfg(target_endian = "little")]
11    unsafe {
12        &*(u as *const usize as *const T)
13    }
14}
15
16#[inline(always)]
17pub(crate) const fn into_variant<T: Copy>(u: usize) -> T {
18    *cast_variant::<T>(&u)
19}
20
21#[inline(always)]
22pub(crate) const fn to_usize<T>(t: &T) -> usize {
23    macro_rules! as_usize {
24        ($type:ident) => {
25            unsafe { *(t as *const T as *const $type) as usize }
26        };
27    }
28
29    match const { core::mem::size_of::<T>() } {
30        1 => as_usize!(u8),
31        2 => as_usize!(u16),
32        4 => as_usize!(u32),
33
34        #[cfg(target_pointer_width = "64")]
35        8 => as_usize!(u64),
36        #[cfg(target_pointer_width = "32")]
37        8 => panic!(
38            "enum-table: Cannot handle 64-bit enum discriminants on 32-bit architecture. Consider using smaller discriminant values or compile for 64-bit target."
39        ),
40
41        _ => panic!(
42            "enum-table: Enum discriminants larger than 64 bits are not supported. This is likely due to an extremely large enum or invalid memory layout."
43        ),
44    }
45}
46
47pub const fn sort_variants<const N: usize, T>(mut arr: [T; N]) -> [T; N] {
48    let mut i = 1;
49    while i < N {
50        let mut j = i;
51        while j > 0 && to_usize(&arr[j]) < to_usize(&arr[j - 1]) {
52            arr.swap(j, j - 1);
53            j -= 1;
54        }
55        i += 1;
56    }
57    arr
58}
59
60#[cfg(debug_assertions)]
61pub(crate) const fn is_sorted<T>(arr: &[T]) -> bool {
62    let mut i = 0;
63    while i < arr.len() - 1 {
64        if to_usize(&arr[i]) > to_usize(&arr[i + 1]) {
65            return false;
66        }
67        i += 1;
68    }
69    true
70}