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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
use super::utils;
use crate::{iter::*, Position, Table};
use std::{
    iter::FromIterator,
    mem,
    ops::{Index, IndexMut},
};

/// Represents an inmemory table containing rows & columns of some data `T`
/// with a fixed capacity across both rows and columns
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde-1", derive(serde::Serialize, serde::Deserialize))]
#[repr(transparent)]
pub struct FixedTable<T: Default, const ROW: usize, const COL: usize>(
    #[cfg_attr(
        feature = "serde-1",
        serde(
            bound(
                serialize = "T: serde::Serialize",
                deserialize = "T: serde::Deserialize<'de>"
            ),
            serialize_with = "utils::serialize_table_array",
            deserialize_with = "utils::deserialize_table_array"
        )
    )]
    [[T; COL]; ROW],
);

impl<T: Default, const ROW: usize, const COL: usize> FixedTable<T, ROW, COL> {
    /// Creates a new, empty table
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns an iterator over the cells and their positions within the table
    pub fn iter(&self) -> ZipPosition<&T, Cells<T, FixedTable<T, ROW, COL>>> {
        self.into_iter()
    }
}

impl<T: Default, const ROW: usize, const COL: usize> Default for FixedTable<T, ROW, COL> {
    fn default() -> Self {
        Self(utils::default_table_array::<T, ROW, COL>())
    }
}

impl<T: Default, const ROW: usize, const COL: usize> Table for FixedTable<T, ROW, COL> {
    type Data = T;

    fn row_cnt(&self) -> usize {
        ROW
    }

    fn col_cnt(&self) -> usize {
        COL
    }

    fn get_cell(&self, row: usize, col: usize) -> Option<&Self::Data> {
        if row < ROW && col < COL {
            Some(&self.0[row][col])
        } else {
            None
        }
    }

    fn get_mut_cell(&mut self, row: usize, col: usize) -> Option<&mut Self::Data> {
        if row < ROW && col < COL {
            Some(&mut self.0[row][col])
        } else {
            None
        }
    }

    fn insert_cell(&mut self, row: usize, col: usize, value: Self::Data) -> Option<Self::Data> {
        if row < ROW && col < COL {
            Some(mem::replace(&mut self.0[row][col], value))
        } else {
            None
        }
    }

    fn remove_cell(&mut self, row: usize, col: usize) -> Option<T> {
        self.insert_cell(row, col, T::default())
    }
}

impl<T: Default, const ROW: usize, const COL: usize> From<[[T; COL]; ROW]>
    for FixedTable<T, ROW, COL>
{
    fn from(cells: [[T; COL]; ROW]) -> Self {
        Self(cells)
    }
}

impl<'a, T: Default, const ROW: usize, const COL: usize> IntoIterator
    for &'a FixedTable<T, ROW, COL>
{
    type Item = (Position, &'a T);
    type IntoIter = ZipPosition<&'a T, Cells<'a, T, FixedTable<T, ROW, COL>>>;

    /// Converts into an iterator over the table's cells' positions and values
    fn into_iter(self) -> Self::IntoIter {
        self.cells().zip_with_position()
    }
}

impl<T: Default, const ROW: usize, const COL: usize> IntoIterator for FixedTable<T, ROW, COL> {
    type Item = (Position, T);
    type IntoIter = ZipPosition<T, IntoCells<T, FixedTable<T, ROW, COL>>>;

    /// Converts into an iterator over the table's cells' positions and values
    fn into_iter(self) -> Self::IntoIter {
        self.into_cells().zip_with_position()
    }
}

impl<T: Default, V: Into<T>, const ROW: usize, const COL: usize> FromIterator<(usize, usize, V)>
    for FixedTable<T, ROW, COL>
{
    /// Produces a table from the provided iterator of (row, col, value). All
    /// values that would go outside of the range of the table will be dropped.
    fn from_iter<I: IntoIterator<Item = (usize, usize, V)>>(iter: I) -> Self {
        let mut table = Self::new();
        for (row, col, value) in iter.into_iter() {
            table.insert_cell(row, col, value.into());
        }
        table
    }
}

impl<T: Default, V: Into<T>, const ROW: usize, const COL: usize> FromIterator<(Position, V)>
    for FixedTable<T, ROW, COL>
{
    /// Produces a table from the provided iterator of (position, value). All
    /// values that would go outside of the range of the table will be dropped.
    fn from_iter<I: IntoIterator<Item = (Position, V)>>(iter: I) -> Self {
        let mut table = Self::new();
        for (pos, value) in iter.into_iter() {
            table.insert_cell(pos.row, pos.col, value.into());
        }
        table
    }
}

impl<T: Default, const ROW: usize, const COL: usize> Index<(usize, usize)>
    for FixedTable<T, ROW, COL>
{
    type Output = T;

    /// Indexes into a table by a specific row and column, returning a
    /// reference to the cell if it exists, otherwise panicking
    fn index(&self, (row, col): (usize, usize)) -> &Self::Output {
        self.get_cell(row, col)
            .expect("Row/Column index out of range")
    }
}

impl<T: Default, const ROW: usize, const COL: usize> IndexMut<(usize, usize)>
    for FixedTable<T, ROW, COL>
{
    /// Indexes into a table by a specific row and column, returning a mutable
    /// reference to the cell if it exists, otherwise panicking
    fn index_mut(&mut self, (row, col): (usize, usize)) -> &mut Self::Output {
        self.get_mut_cell(row, col)
            .expect("Row/Column index out of range")
    }
}

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

    #[test]
    fn row_cnt_should_match_fixed_row_size() {
        let table: FixedTable<usize, 0, 0> = FixedTable::new();
        assert_eq!(table.row_cnt(), 0);

        let table: FixedTable<usize, 4, 0> = FixedTable::new();
        assert_eq!(table.row_cnt(), 4);
    }

    #[test]
    fn col_cnt_should_match_fixed_col_size() {
        let table: FixedTable<usize, 0, 0> = FixedTable::new();
        assert_eq!(table.col_cnt(), 0);

        let table: FixedTable<usize, 0, 4> = FixedTable::new();
        assert_eq!(table.col_cnt(), 4);
    }

    #[test]
    fn get_cell_should_return_ref_to_cell_at_location() {
        let table = FixedTable::from([["a", "b"], ["c", "d"]]);
        assert_eq!(table.get_cell(0, 0), Some(&"a"));
        assert_eq!(table.get_cell(0, 1), Some(&"b"));
        assert_eq!(table.get_cell(1, 0), Some(&"c"));
        assert_eq!(table.get_cell(1, 1), Some(&"d"));
        assert_eq!(table.get_cell(1, 2), None);
    }

    #[test]
    fn get_mut_cell_should_return_mut_ref_to_cell_at_location() {
        let mut table = FixedTable::from([["a", "b"], ["c", "d"]]);
        *table.get_mut_cell(0, 0).unwrap() = "e";
        assert_eq!(table.get_cell(0, 0), Some(&"e"));
    }

    #[test]
    fn insert_cell_should_return_previous_cell_and_overwrite_content() {
        let mut table: FixedTable<usize, 3, 3> = FixedTable::new();

        assert_eq!(table.insert_cell(0, 0, 123), Some(usize::default()));
        assert_eq!(table.insert_cell(0, 0, 999), Some(123));
        assert_eq!(table.get_cell(0, 0), Some(&999))
    }

    #[test]
    fn remove_cell_should_return_cell_that_is_removed() {
        let mut table = FixedTable::from([[1, 2], [3, 4]]);

        // NOTE: Because fixed table uses a default value when removing,
        //       we should see the default value of a number (0) be injected
        assert_eq!(table.remove_cell(0, 0), Some(1));
        assert_eq!(table.remove_cell(0, 0), Some(0));
    }

    #[test]
    fn index_by_row_and_column_should_return_cell_ref() {
        let table = FixedTable::from([[1, 2, 3]]);
        assert_eq!(table[(0, 1)], 2);
    }

    #[test]
    #[should_panic]
    fn index_by_row_and_column_should_panic_if_cell_not_found() {
        let table = FixedTable::from([[1, 2, 3]]);
        let _ = table[(1, 0)];
    }

    #[test]
    fn index_mut_by_row_and_column_should_return_mutable_cell() {
        let mut table = FixedTable::from([[1, 2, 3]]);
        table[(0, 1)] = 999;

        // Verify on the altered cell was changed
        assert_eq!(table[(0, 0)], 1);
        assert_eq!(table[(0, 1)], 999);
        assert_eq!(table[(0, 2)], 3);
    }

    #[test]
    #[should_panic]
    fn index_mut_by_row_and_column_should_panic_if_cell_not_found() {
        let mut table = FixedTable::from([[1, 2, 3]]);
        table[(1, 0)] = 999;
    }
}