use rmp_serde::{Serializer, from_slice};
use serde::Serialize;
use super::model::RuleLibrary;
use crate::error::{RswResult, RswappalyzerError};
use crate::config::GlobalConfig;
pub struct RuleCacheManager;
impl RuleCacheManager {
pub async fn load_from_cache(config: &GlobalConfig) -> RswResult<RuleLibrary> {
let cache_path = &config.rule_cache_path;
let cache_data = tokio::fs::read(cache_path).await?;
let rule_lib = from_slice(&cache_data)
.map_err(|e| RswappalyzerError::MsgPackError(format!("反序列化失败:{}", e)))?;
Ok(rule_lib)
}
pub async fn save_to_cache(config: &GlobalConfig, rule_lib: &RuleLibrary) -> RswResult<()> {
let cache_path = &config.rule_cache_path;
let mut cache_data = Vec::new();
rule_lib.serialize(&mut Serializer::new(&mut cache_data))
.map_err(|e| RswappalyzerError::MsgPackError(format!("序列化失败:{}", e)))?;
tokio::fs::write(cache_path, cache_data).await?;
Ok(())
}
pub async fn clear_cache(config: &GlobalConfig) -> RswResult<()> {
let cache_path = &config.rule_cache_path;
if cache_path.exists() {
tokio::fs::remove_file(cache_path).await?;
}
Ok(())
}
}