idem_handler_config/
config_cache.rs1use dashmap::DashMap;
2use once_cell::sync::Lazy;
3use std::sync::Arc;
4use std::fs;
5
6static FILE_CACHE: Lazy<DashMap<String, Arc<String>>> = Lazy::new(DashMap::new);
7
8pub fn get_file(file_path: &str) -> Result<Arc<String>, String> {
9 if let Some(contents) = FILE_CACHE.get(file_path) {
10 return Ok(contents.clone());
11 }
12 let contents = Arc::new(
13 fs::read_to_string(file_path)
14 .map_err(|e| format!("Failed to read file: {}", e))?,
15 );
16 FILE_CACHE.insert(file_path.to_string(), contents.clone());
17 Ok(contents)
18}
19
20pub fn init_or_replace_config(file_path: &str) -> Result<(), String> {
21 let contents = Arc::new(
22 fs::read_to_string(file_path)
23 .map_err(|e| format!("Failed to read file: {}", e))?,
24 );
25 FILE_CACHE.insert(file_path.to_string(), contents);
26 Ok(())
27}
28
29pub fn clear_cache() {
30 FILE_CACHE.clear();
31}
32
33#[cfg(test)]
34mod test {
35 use crate::config_cache::{clear_cache, get_file};
36 use std::sync::Arc;
37
38 #[test]
39 fn test_cache() {
40 let file_arc1 = get_file("./test/test.file").unwrap();
41 let file_arc2 = get_file("./test/test.file").unwrap();
42 assert!(Arc::ptr_eq(&file_arc1, &file_arc2));
43
44 clear_cache();
45 let file_arc3 = get_file("./test/test.file").unwrap();
46 assert!(!Arc::ptr_eq(&file_arc1, &file_arc3));
47 }
48}