screeps_pathfinding/utils/cache/
lcm_cache_struct.rs

1use std::collections::HashMap;
2
3use screeps::{LocalCostMatrix, RoomName};
4
5/// A simple passthrough cache that preferentially returns cached
6/// LCM data for a room, dynamically generating LCM data as-needed
7/// from a user-provided closure and caching it before returning it.
8#[derive(Debug, Clone)]
9pub struct LCMCache {
10    cache: HashMap<RoomName, LocalCostMatrix>,
11}
12
13impl Default for LCMCache {
14    fn default() -> Self {
15        Self::new()
16    }
17}
18
19impl LCMCache {
20    /// Initializes a new, empty LCM cache.
21    pub fn new() -> Self {
22        Self {
23            cache: HashMap::new(),
24        }
25    }
26
27    /// Returns the cached LCM, if it exists.
28    ///
29    /// Returns None if the LCM isn't cached.
30    pub fn get_cached_lcm(&self, room_name: &RoomName) -> Option<&LocalCostMatrix> {
31        self.cache.get(room_name)
32    }
33
34    /// Returns whether an LCM is cached for a particular room.
35    pub fn is_lcm_cached(&self, room_name: &RoomName) -> bool {
36        self.cache.contains_key(room_name)
37    }
38
39    /// Returns the room LCM, generating and caching it if it's not already cached.
40    pub fn get_lcm(
41        &mut self,
42        room_name: &RoomName,
43        generator_fn: impl FnOnce(&RoomName) -> LocalCostMatrix,
44    ) -> &LocalCostMatrix {
45        if !self.is_lcm_cached(room_name) {
46            // We don't have a cached copy of the LCM, generate and cache it
47            let lcm = generator_fn(room_name);
48            let _ = self.cache.insert(*room_name, lcm);
49        }
50
51        self.get_cached_lcm(room_name).unwrap() // We know this is okay, because we generated and inserted a new LCM for this entry
52    }
53
54    /// Updates the LCM cache for a specific room.
55    ///
56    /// This allows for pre-loading the cache with any existing
57    /// room LCM data you might already have available.
58    pub fn update_cached_lcm(&mut self, room_name: RoomName, lcm: LocalCostMatrix) {
59        let _ = self.cache.insert(room_name, lcm);
60    }
61
62    /// Removes the LCM cached for a specific room.
63    pub fn remove_cached_lcm(&mut self, room_name: &RoomName) {
64        self.cache.remove(room_name);
65    }
66}