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
use crate::ArenaIndex;
use alloc::vec::Vec;
use core::{
    fmt::{self, Debug},
    marker::PhantomData,
    ops::{Index, IndexMut},
};

/// Stores components for entities backed by a [`Vec`].
pub struct ComponentVec<Idx, T> {
    components: Vec<Option<T>>,
    marker: PhantomData<fn() -> Idx>,
}

/// [`ComponentVec`] does not store `Idx` therefore it is `Send` without its bound.
unsafe impl<Idx, T> Send for ComponentVec<Idx, T> where T: Send {}

/// [`ComponentVec`] does not store `Idx` therefore it is `Sync` without its bound.
unsafe impl<Idx, T> Sync for ComponentVec<Idx, T> where T: Sync {}

impl<Idx, T> Debug for ComponentVec<Idx, T>
where
    T: Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ComponentVec")
            .field("components", &DebugComponents(&self.components))
            .finish()
    }
}

struct DebugComponents<'a, T>(&'a [Option<T>]);

impl<'a, T> Debug for DebugComponents<'a, T>
where
    T: Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut map = f.debug_map();
        let components = self
            .0
            .iter()
            .enumerate()
            .filter_map(|(n, component)| component.as_ref().map(|c| (n, c)));
        for (idx, component) in components {
            map.entry(&idx, component);
        }
        map.finish()
    }
}

impl<Idx, T> Default for ComponentVec<Idx, T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<Idx, T> PartialEq for ComponentVec<Idx, T>
where
    T: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.components.eq(&other.components)
    }
}

impl<Idx, T> Eq for ComponentVec<Idx, T> where T: Eq {}

impl<Idx, T> ComponentVec<Idx, T> {
    /// Creates a new empty [`ComponentVec`].
    pub fn new() -> Self {
        Self {
            components: Vec::new(),
            marker: PhantomData,
        }
    }

    /// Clears all components from the [`ComponentVec`].
    pub fn clear(&mut self) {
        self.components.clear();
    }
}

impl<Idx, T> ComponentVec<Idx, T>
where
    Idx: ArenaIndex,
{
    /// Sets the `component` for the entity at `index`.
    ///
    /// Returns the old component of the same entity if any.
    pub fn set(&mut self, index: Idx, component: T) -> Option<T> {
        let index = index.into_usize();
        if index >= self.components.len() {
            // The underlying vector does not have enough capacity
            // and is required to be enlarged.
            self.components.resize_with(index + 1, || None);
        }
        self.components[index].replace(component)
    }

    /// Unsets the component for the entity at `index` and returns it if any.
    pub fn unset(&mut self, index: Idx) -> Option<T> {
        self.components
            .get_mut(index.into_usize())
            .and_then(Option::take)
    }

    /// Returns a shared reference to the component at the `index` if any.
    ///
    /// Returns `None` if no component is stored under the `index`.
    #[inline]
    pub fn get(&self, index: Idx) -> Option<&T> {
        self.components
            .get(index.into_usize())
            .and_then(Option::as_ref)
    }

    /// Returns an exclusive reference to the component at the `index` if any.
    ///
    /// Returns `None` if no component is stored under the `index`.
    #[inline]
    pub fn get_mut(&mut self, index: Idx) -> Option<&mut T> {
        self.components
            .get_mut(index.into_usize())
            .and_then(Option::as_mut)
    }
}

impl<Idx, T> Index<Idx> for ComponentVec<Idx, T>
where
    Idx: ArenaIndex,
{
    type Output = T;

    #[inline]
    fn index(&self, index: Idx) -> &Self::Output {
        self.get(index)
            .unwrap_or_else(|| panic!("missing component at index: {}", index.into_usize()))
    }
}

impl<Idx, T> IndexMut<Idx> for ComponentVec<Idx, T>
where
    Idx: ArenaIndex,
{
    #[inline]
    fn index_mut(&mut self, index: Idx) -> &mut Self::Output {
        self.get_mut(index)
            .unwrap_or_else(|| panic!("missing component at index: {}", index.into_usize()))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Add `n` components and perform checks along the way.
    fn add_components(vec: &mut ComponentVec<usize, String>, n: usize) {
        for i in 0..n {
            let mut str = format!("{i}");
            assert!(vec.get(i).is_none());
            assert!(vec.get_mut(i).is_none());
            assert!(vec.set(i, str.clone()).is_none());
            assert_eq!(vec.get(i), Some(&str));
            assert_eq!(vec.get_mut(i), Some(&mut str));
            assert_eq!(&vec[i], &str);
            assert_eq!(&mut vec[i], &mut str);
        }
    }

    #[test]
    fn it_works() {
        let mut vec = <ComponentVec<usize, String>>::new();
        let n = 10;
        add_components(&mut vec, n);
        // Remove components in reverse order for fun.
        // Check if components have been removed properly.
        for i in (0..n).rev() {
            let str = format!("{i}");
            assert_eq!(vec.unset(i), Some(str));
            assert!(vec.get(i).is_none());
            assert!(vec.get_mut(i).is_none());
        }
    }

    #[test]
    fn clear_works() {
        let mut vec = <ComponentVec<usize, String>>::new();
        let n = 10;
        add_components(&mut vec, n);
        // Clear component vec and check if components have been removed properly.
        vec.clear();
        for i in 0..n {
            assert!(vec.get(i).is_none());
            assert!(vec.get_mut(i).is_none());
        }
    }

    #[test]
    fn debug_works() {
        let mut vec = <ComponentVec<usize, String>>::new();
        add_components(&mut vec, 4);
        {
            let debug_str = format!("{vec:?}");
            let expected_str = "\
                ComponentVec { components: {0: \"0\", 1: \"1\", 2: \"2\", 3: \"3\"} }\
            ";
            assert_eq!(debug_str, expected_str);
        }
        {
            let debug_str = format!("{vec:#?}");
            let expected_str = "\
                ComponentVec {\n    \
                    components: {\n        \
                        0: \"0\",\n        \
                        1: \"1\",\n        \
                        2: \"2\",\n        \
                        3: \"3\",\n    \
                    },\n}\
            ";
            assert_eq!(debug_str, expected_str);
        }
    }
}