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
use std::collections::HashMap;
use std::iter::FusedIterator;

use gridly::prelude::*;

#[derive(Debug, Clone)]
pub struct SparseGrid<T: Clone + PartialEq> {
    root: Location,
    dimensions: Vector,
    default: T,
    storage: HashMap<Location, T>,
}

impl<T: Clone + PartialEq> SparseGrid<T> {
    pub fn new(dimensions: Vector, default: T) -> Self {
        Self::new_rooted(Location::zero(), dimensions, default)
    }

    pub fn new_rooted(root: Location, dimensions: Vector, default: T) -> Self {
        Self {
            root,
            dimensions,
            default,
            storage: HashMap::new(),
        }
    }

    pub fn get_default(&self) -> &T {
        &self.default
    }

    /// Remove all entries from the grid that compare equal to the default
    pub fn clean(&mut self) {
        let default = &self.default;
        self.storage.retain(move |_, value| value != default)
    }

    /// Get an iterator over all of the occupied entries in the grid, in an arbitrary order.
    pub fn occuppied_entries(
        &self,
    ) -> impl Iterator<Item = (&Location, &T)> + FusedIterator + Clone {
        let default = &self.default;
        self.storage
            .iter()
            .filter(move |(_, value)| *value != default)
    }

    pub fn occuppied_entries_mut(
        &mut self,
    ) -> impl Iterator<Item = (&Location, &mut T)> + FusedIterator {
        let default = &self.default;
        self.storage
            .iter_mut()
            .filter(move |(_, value)| *value != default)
    }
}

impl<T: Clone + PartialEq> GridBounds for SparseGrid<T> {
    fn dimensions(&self) -> Vector {
        self.dimensions
    }

    fn root(&self) -> Location {
        self.root
    }
}

impl<T: Clone + PartialEq> BaseGrid for SparseGrid<T> {
    type Item = T;

    unsafe fn get_unchecked(&self, loc: &Location) -> &T {
        self.storage.get(loc).unwrap_or(&self.default)
    }
}

impl<T: Clone + PartialEq> BaseGridMut for SparseGrid<T> {
    unsafe fn get_unchecked_mut(&mut self, loc: &Location) -> &mut T {
        let default = &self.default;
        self.storage
            .entry(*loc)
            .or_insert_with(move || default.clone())
    }

    unsafe fn set_unchecked(&mut self, loc: &Location, value: T) {
        if value == self.default {
            self.storage.remove(loc);
        } else {
            self.storage.insert(*loc, value);
        }
    }
}