use crate::context::StatContext;
use crate::stat_id::StatId;
use std::collections::HashMap;
pub trait StatSource: Send + Sync {
fn get_value(&self, stat_id: &StatId, context: &StatContext) -> f64;
}
#[derive(Debug, Clone)]
pub struct ConstantSource(pub f64);
impl StatSource for ConstantSource {
fn get_value(&self, _stat_id: &StatId, _context: &StatContext) -> f64 {
self.0
}
}
#[derive(Debug, Clone)]
pub struct MapSource {
values: HashMap<StatId, f64>,
}
impl MapSource {
pub fn new(values: HashMap<StatId, f64>) -> Self {
Self { values }
}
pub fn empty() -> Self {
Self {
values: HashMap::new(),
}
}
pub fn insert(&mut self, stat_id: StatId, value: f64) {
self.values.insert(stat_id, value);
}
}
impl StatSource for MapSource {
fn get_value(&self, stat_id: &StatId, _context: &StatContext) -> f64 {
self.values.get(stat_id).copied().unwrap_or(0.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_constant_source() {
let source = ConstantSource(100.0);
let context = StatContext::new();
let stat_id = StatId::from_str("HP");
assert_eq!(source.get_value(&stat_id, &context), 100.0);
}
#[test]
fn test_map_source() {
let mut source = MapSource::empty();
let hp_id = StatId::from_str("HP");
let atk_id = StatId::from_str("ATK");
source.insert(hp_id.clone(), 100.0);
source.insert(atk_id.clone(), 50.0);
let context = StatContext::new();
assert_eq!(source.get_value(&hp_id, &context), 100.0);
assert_eq!(source.get_value(&atk_id, &context), 50.0);
assert_eq!(
source.get_value(&StatId::from_str("MISSING"), &context),
0.0
);
}
}