dod_table/lib.rs
1use core::array;
2use std::slice::{Iter, IterMut};
3
4/// A contiguous memory block.
5///
6/// # Example:
7/// ```
8/// // Make sure that the type used in the table implements the Default trait.
9/// #[derive(Default)]
10/// struct Entity {
11/// x: f32,
12/// y: f32,
13/// }
14///
15/// struct Data {
16/// // Memory reserved for (in this specific example) 512 entities.
17/// entities: Table<Entity, 512>
18/// }
19/// ```
20pub struct Table<T, const N: usize> {
21 elements: [T; N],
22}
23
24impl<T, const N: usize> Table<T, N>
25where
26 T: Default,
27{
28 /// Get a reference to an element at the given index.
29 pub fn get(&self, i: usize) -> &T {
30 &self.elements[i]
31 }
32
33 /// Get a mutable reference to an element at the given index.
34 pub fn get_mut(&mut self, i: usize) -> &mut T {
35 &mut self.elements[i]
36 }
37
38 /// Set an element at the given index.
39 pub fn set(&mut self, i: usize, e: T) {
40 self.elements[i] = e;
41 }
42
43 /// Iterate over references of the elements.
44 pub fn iter(&self) -> Iter<T> {
45 self.elements.iter()
46 }
47
48 /// Iterate over mutable references of the elements.
49 pub fn iter_mut(&mut self) -> IterMut<T> {
50 self.elements.iter_mut()
51 }
52
53 /// Reset the element at the given index back to its default values (AKA zeroing).
54 pub fn zero(&mut self, i: usize) {
55 self.elements[i] = T::default()
56 }
57}
58
59impl<T, const N: usize> Default for Table<T, N>
60where
61 T: Default,
62{
63 fn default() -> Self {
64 Self {
65 elements: array::from_fn(|_i| T::default()),
66 }
67 }
68}