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 {
26            dims,
27            cells: vec![cell; dims.size()],
28        }
29    }
30}
31
32impl<T: Default> GridMap<T> {
33    //! Construction: Default
34
35    /// Creates a new grid map with the default cell.
36    pub fn new_default(dims: Dim) -> Self {
37        Self::new(dims, |_| T::default())
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    use crate::{Dim, GridMap, Loc};
44
45    #[test]
46    fn new() {
47        let dims: Dim = Dim::new(3, 2);
48        let map: GridMap<Loc> = GridMap::new(dims, |loc| loc);
49        for loc in dims.locs() {
50            assert_eq!(*map.get(loc), loc);
51        }
52    }
53
54    #[test]
55    fn new_clone() {
56        let dims: Dim = Dim::new(3, 3);
57        let map: GridMap<u8> = GridMap::new_clone(dims, 42);
58        for loc in dims.locs() {
59            assert_eq!(*map.get(loc), 42);
60        }
61    }
62
63    #[test]
64    fn new_default() {
65        let dims: Dim = Dim::new(2, 2);
66        let map: GridMap<u8> = GridMap::new_default(dims);
67        for loc in dims.locs() {
68            assert_eq!(*map.get(loc), 0);
69        }
70    }
71}