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
use core::array;

/// A contiguous memory block.
///
/// # Example:
/// ```
/// // Make sure that the type used in the table implements the Default trait.
/// #[derive(Default)]
/// struct Entity {
///     x: f32,
///     y: f32,   
/// }
///
/// struct Data {
///     // Memory reserved for (in this specific example) 512 entities.
///     entities: Table<Entity, 512>
/// }
/// ```
pub struct Table<T, const N: usize> {
    elements: [T; N],
}

impl<T, const N: usize> Table<T, N>
where
    T: Default,
{
    /// Get a reference to an element at the given index.
    pub fn get(&self, i: usize) -> &T {
        &self.elements[i]
    }

    /// Get a mutable reference to an element at the given index.
    pub fn get_mut(&mut self, i: usize) -> &mut T {
        &mut self.elements[i]
    }

    /// Set an element at the given index.
    pub fn set(&mut self, i: usize, e: T) {
        self.elements[i] = e;
    }

    /// Get a reference to the first element that satisfies the given predicate.
    pub fn find<P>(&self, predicate: P) -> Option<(usize, &T)>
    where
        P: Fn(&T) -> bool,
    {
        self.elements
            .iter()
            .enumerate()
            .find(|(_idx, e)| predicate(e))
    }

    /// Get a mutable reference to the first element that satisfies the given predicate.
    pub fn find_mut<P>(&mut self, predicate: P) -> Option<(usize, &mut T)>
    where
        P: Fn(&T) -> bool,
    {
        self.elements
            .iter_mut()
            .enumerate()
            .find(|(_idx, e)| predicate(e))
    }

    /// Reset the element at the given index back to its default values (AKA zeroing).
    pub fn zero(&mut self, i: usize) {
        self.elements[i] = T::default()
    }
}

impl<T, const N: usize> Default for Table<T, N>
where
    T: Default,
{
    fn default() -> Self {
        Self {
            elements: array::from_fn(|_i| T::default()),
        }
    }
}