use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct StatContext {
data: HashMap<String, serde_json::Value>,
}
impl StatContext {
pub fn new() -> Self {
Self::default()
}
pub fn set(&mut self, key: impl Into<String>, value: impl Serialize) {
if let Ok(json_value) = serde_json::to_value(value) {
self.data.insert(key.into(), json_value);
}
}
pub fn get<T: for<'de> Deserialize<'de>>(&self, key: &str) -> Option<T> {
self.data
.get(key)
.and_then(|v| serde_json::from_value(v.clone()).ok())
}
pub fn contains_key(&self, key: &str) -> bool {
self.data.contains_key(key)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_context_set_get() {
let mut ctx = StatContext::new();
ctx.set("difficulty", 5);
let difficulty: Option<i32> = ctx.get("difficulty");
assert_eq!(difficulty, Some(5));
}
#[test]
fn test_context_missing_key() {
let ctx = StatContext::new();
let value: Option<i32> = ctx.get("missing");
assert_eq!(value, None);
}
}