1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
pub const MAP_SIZE: usize = u8::MAX as usize;

macro_rules! build_map_helper {
    ($data: expr, $val_fn: expr) => {
        unsafe {
            let mut map: Vec<V> = Vec::with_capacity(MAP_SIZE);
            map.set_len(MAP_SIZE);
            for ele in $data {
                let (key, val) = $val_fn(ele);
                let idx = *(&key as *const E as *const u8) as usize;
                std::ptr::write(&mut map[idx] as *mut _, val);
            }
            map
        }
    };
}

pub fn build_map<E, V, D, F>(data: &[D], val_fn: F) -> Vec<V>
where
    E: Copy,
    F: Fn(&D) -> (E, V),
{
    assert_eq!(
        std::mem::size_of::<E>(),
        1,
        "Size of {} must be 1",
        std::any::type_name::<E>()
    );
    build_map_helper!(data, val_fn)
}

pub fn build_map_mut_data<E, V, D, F>(data: &mut [D], val_fn: F) -> Vec<V>
where
    E: Copy,
    F: Fn(&mut D) -> (E, V),
{
    assert_eq!(
        std::mem::size_of::<E>(),
        1,
        "Size of {} must be 1",
        std::any::type_name::<E>()
    );
    build_map_helper!(data, val_fn)
}

pub struct EnumMap<E, V>
where
    E: Copy,
{
    pub map: Vec<V>,
    _phantom: std::marker::PhantomData<E>,
}

impl<E, V> EnumMap<E, V>
where
    E: Copy,
{
    pub fn new<D, F>(data: &[D], val_fn: F) -> Self
    where
        F: Fn(&D) -> (E, V),
    {
        Self {
            map: build_map(data, val_fn),
            _phantom: std::marker::PhantomData,
        }
    }

    pub fn new_mut_data<D, F>(data: &mut [D], val_fn: F) -> Self
    where
        F: Fn(&mut D) -> (E, V),
    {
        Self {
            map: build_map_mut_data(data, val_fn),
            _phantom: std::marker::PhantomData,
        }
    }

    pub fn get(&self, key: E) -> &V {
        unsafe { &self.map[*(&key as *const E as *const u8) as usize] }
    }

    pub fn get_mut(&mut self, key: E) -> &mut V {
        unsafe { &mut self.map[*(&key as *const E as *const u8) as usize] }
    }
}