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
use direction::{Direction, DirectionBitmap, NUM_DIRECTIONS};

const NUM_NEIGHBOURS: usize = NUM_DIRECTIONS;

/// Table for managing counts associated with directions.
/// This is used by the generated spatial hash as
/// storage for the `neighbour_count` aggregate.
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub struct NeighbourCount {
    neighbours: [u8; NUM_NEIGHBOURS],
}

impl NeighbourCount {
    pub fn new() -> Self {
        NeighbourCount {
            neighbours: [0; NUM_NEIGHBOURS],
        }
    }

    pub fn inc(&mut self, direction: Direction) {
        self.neighbours[direction as usize] += 1;
    }

    pub fn dec(&mut self, direction: Direction) {
        self.neighbours[direction as usize] -= 1;
    }

    pub fn get(&self, direction: Direction) -> u8 {
        self.neighbours[direction as usize]
    }

    pub fn has(&self, direction: Direction) -> bool {
        self.neighbours[direction as usize] != 0
    }

    pub fn bitmap_raw(&self) -> u8 {
        (((self.neighbours[0] != 0) as u8) << 0) |
        (((self.neighbours[1] != 0) as u8) << 1) |
        (((self.neighbours[2] != 0) as u8) << 2) |
        (((self.neighbours[3] != 0) as u8) << 3) |
        (((self.neighbours[4] != 0) as u8) << 4) |
        (((self.neighbours[5] != 0) as u8) << 5) |
        (((self.neighbours[6] != 0) as u8) << 6) |
        (((self.neighbours[7] != 0) as u8) << 7)
    }

    pub fn bitmap(&self) -> DirectionBitmap {
        DirectionBitmap::new(self.bitmap_raw())
    }
}

impl Default for NeighbourCount {
    fn default() -> Self {
        Self::new()
    }
}