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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
use std::fmt::{Debug, Formatter};
use std::marker::PhantomData;
use std::ops::{Deref, Index, IndexMut};

use crate::Enumerated;

/// A key-value table optimized for Enums used as keys. Initialized with `V`'s [Default] values.
///
/// ```
/// use enum_collections::{EnumTable, Enumerated};
/// #[derive(Enumerated)]
/// enum Letter {
///     A,
///     B,
/// }
///
/// let mut map: EnumTable<Letter, u8> = EnumTable::new();
/// map[Letter::A] = 42;
/// assert_eq!(42u8, map[Letter::A]);
/// assert_eq!(u8::default(), map[Letter::B]);
/// ```
pub struct EnumTable<K, V> {
    values: Box<[V]>,
    _key_phantom_data: PhantomData<K>,
}

impl<K, V> EnumTable<K, V>
where
    K: Enumerated,
{
    pub fn from_fn(cb: impl FnMut(&K) -> V) -> Self {
        Self {
            values: K::VARIANTS.iter().map(cb).collect::<Vec<V>>().into(),
            _key_phantom_data: Default::default(),
        }
    }
}

impl<K, V> EnumTable<K, V>
where
    K: Enumerated,
    V: Default,
{
    /// Creates a new [EnumTable], with pre-allocated space for all keys of the enum `K`. With the underlying array righsized,
    /// no resizing is further required. All values are initialized with `V`'s [Default] value.
    pub fn new() -> Self {
        Self {
            values: K::VARIANTS
                .iter()
                .map(|_| V::default())
                .collect::<Vec<V>>()
                .into(),
            _key_phantom_data: PhantomData {},
        }
    }

    /// Resets value of type `V` corresponding to `key` to its default by calling its [Default] trait implementation.
    ///
    /// ### Args
    /// - `key` - The instance of `K` pointing at the slot to reset to default.
    pub fn reset(&mut self, key: K) {
        self.values[key.position()] = V::default();
    }
}

impl<K, V> Default for EnumTable<K, V>
where
    K: Enumerated,
    V: Default,
{
    /// Constructs a new instance, capable of holding all values of key `K` without further resizing.
    fn default() -> Self {
        Self::new()
    }
}

impl<K, V> Index<K> for EnumTable<K, V>
where
    K: Enumerated,
    V: Default,
{
    type Output = V;

    fn index(&self, key: K) -> &Self::Output {
        &self.values[key.position()]
    }
}

impl<K, V> IndexMut<K> for EnumTable<K, V>
where
    K: Enumerated,
    V: Default,
{
    fn index_mut(&mut self, key: K) -> &mut Self::Output {
        &mut self.values[key.position()]
    }
}

impl<F, K, V> From<F> for EnumTable<K, V>
where
    K: Enumerated,
    F: FnMut(&K) -> V,
{
    fn from(cb: F) -> Self {
        Self::from_fn(cb)
    }
}

#[cfg(feature = "debug")]
impl<K, V> Debug for EnumTable<K, V>
where
    K: Enumerated + Debug,
    V: Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        // Values are stored in the EnumTable's backing array in the same order as enum's variants
        f.debug_map()
            .entries(
                K::VARIANTS
                    .iter()
                    .enumerate()
                    .map(|(index, variant)| (variant, &self.values[index])),
            )
            .finish()
    }
}

#[cfg(feature = "eq")]
impl<K, V> PartialEq<Self> for EnumTable<K, V>
where
    K: Enumerated,
    V: Default + PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.values.deref().eq(other.values.deref())
    }
}

#[cfg(feature = "eq")]
impl<K, V> Eq for EnumTable<K, V>
where
    K: Enumerated,
    V: Default + Eq,
{
}

#[cfg(test)]
mod tests {
    use super::EnumTable;
    use crate::Enumerated;

    /// No Debug derived on purpose, the crate must be usable without [std::fmt::Debug] derived
    /// for the enum.
    #[derive(Enumerated)]
    pub(super) enum Letter {
        A,
        B,
    }

    #[derive(Eq, PartialEq, Debug, Clone)]
    pub(super) struct Value {
        name: String,
    }

    impl Value {
        pub(super) fn new(name: String) -> Self {
            Self { name }
        }
    }

    impl Default for Value {
        fn default() -> Self {
            Self {
                name: "Non-empty default".to_owned(),
            }
        }
    }

    #[test]
    fn new_all_default() {
        let enum_table = EnumTable::<Letter, Value>::new();
        for index in 0..Letter::VARIANTS.len() {
            assert_eq!(Value::default(), enum_table.values[index]);
        }
    }

    #[test]
    fn get_insert_index_trait() {
        let mut enum_table = EnumTable::<Letter, Value>::new();
        let inserted_value = Value::new("Hello".to_string());
        enum_table[Letter::A] = inserted_value.clone();
        assert_eq!(&inserted_value, &enum_table[Letter::A]);
        assert_eq!(&Value::default(), &enum_table[Letter::B]);
    }

    /// A dedicated enum with [std::fmt::Debug] derived, to test compilation and usability both
    /// with and without `Debug` implemented.
    #[derive(Enumerated, Debug)]
    pub(super) enum LetterDebugDerived {
        A,
        B,
    }

    #[cfg(feature = "debug")]
    #[test]
    fn debug() {
        let mut enum_table = EnumTable::<LetterDebugDerived, i32>::new();
        enum_table[LetterDebugDerived::A] = 42;
        let debug_output = format!("{enum_table:?}");
        let expected_output = "{A: 42, B: 0}";
        assert_eq!(expected_output, debug_output);
    }

    #[cfg(feature = "eq")]
    #[test]
    fn eq() {
        let mut first_table = EnumTable::<LetterDebugDerived, i32>::new();
        first_table[LetterDebugDerived::A] = 42;
        let mut second_table = EnumTable::<LetterDebugDerived, i32>::new();
        second_table[LetterDebugDerived::A] = 42;
        assert_eq!(first_table, second_table);
        second_table[LetterDebugDerived::B] = 42;
        debug_assert_ne!(first_table, second_table);
    }
}