wowlab_engine_gamedata/game_data/resolved_map.rs
1//! [`ResolvedMap`]: a keyed lookup that encodes the empty-vs-populated contract once.
2
3use wowlab_types::sim::{IntMap, IsEnabled};
4
5/// A keyed lookup where an empty map returns the neutral default for every key, but a populated map is authoritative (present -> Some, absent -> None).
6#[derive(Clone, Debug)]
7pub struct ResolvedMap<K, V>
8where
9 K: IsEnabled,
10{
11 map: IntMap<K, V>,
12 default: V,
13}
14
15impl<K, V> ResolvedMap<K, V>
16where
17 K: IsEnabled + Eq + std::hash::Hash,
18{
19 /// Create an empty map (introspection mode) with the neutral value returned for every key.
20 pub fn new(default: V) -> Self {
21 Self {
22 map: IntMap::default(),
23 default,
24 }
25 }
26
27 /// Insert an authoritative value for `key`.
28 pub fn insert(&mut self, key: K, value: V) {
29 self.map.insert(key, value);
30 }
31
32 /// Whether any authoritative data has been resolved.
33 pub fn is_empty(&self) -> bool {
34 self.map.is_empty()
35 }
36
37 /// The neutral default value handed back for every key while the map is empty.
38 pub fn default_value(&self) -> &V {
39 &self.default
40 }
41
42 /// Resolve `key` under the empty-vs-populated contract.
43 pub fn get(&self, key: &K) -> Option<&V> {
44 match self.map.get(key) {
45 Some(value) => Some(value),
46 None if self.map.is_empty() => Some(&self.default),
47 None => None,
48 }
49 }
50
51 /// Mutable access to an authoritative value; the neutral default is never handed out mutably.
52 pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
53 self.map.get_mut(key)
54 }
55}