Skip to main content

grid_map/map/
construct.rs

1use crate::{Dim, GridMap, Loc};
2
3impl<T> GridMap<T> {
4    //! Construction
5
6    /// Creates a new grid map with the `cell_fn`.
7    pub fn new<F>(dims: Dim, cell_fn: F) -> Self
8    where
9        F: Fn(Loc) -> T,
10    {
11        let mut cells: Vec<T> = Vec::with_capacity(dims.size());
12        for i in 0..dims.size() {
13            let loc: Loc = Self::loc(dims, i);
14            cells.push(cell_fn(loc));
15        }
16        Self { dims, cells }
17    }
18}
19
20impl<T: Clone> GridMap<T> {
21    //! Construction: Clone
22
23    /// Creates a new grid map with the cloned `cell`.
24    pub fn new_clone(dims: Dim, cell: T) -> Self {
25        Self::new(dims, |_| cell.clone())
26    }
27}
28
29impl<T: Default> GridMap<T> {
30    //! Construction: Default
31
32    /// Creates a new grid map with the default cell.
33    pub fn new_default(dims: Dim) -> Self {
34        Self::new(dims, |_| T::default())
35    }
36}
37
38#[cfg(test)]
39mod tests {
40    use crate::{Dim, GridMap, Loc};
41
42    #[test]
43    fn new_cell_fn_receives_correct_locs() {
44        let dims: Dim = Dim::new(3, 2);
45        let map: GridMap<Loc> = GridMap::new(dims, |loc| loc);
46        for loc in dims.locs() {
47            assert_eq!(*map.get(loc), loc);
48        }
49    }
50
51    #[test]
52    fn new_clone_all_cells_equal() {
53        let dims: Dim = Dim::new(3, 3);
54        let map: GridMap<u8> = GridMap::new_clone(dims, 42);
55        for loc in dims.locs() {
56            assert_eq!(*map.get(loc), 42);
57        }
58    }
59
60    #[test]
61    fn new_default_all_cells_default() {
62        let dims: Dim = Dim::new(2, 2);
63        let map: GridMap<u8> = GridMap::new_default(dims);
64        for loc in dims.locs() {
65            assert_eq!(*map.get(loc), 0);
66        }
67    }
68}