templito/
func_man.rs

1use crate::*;
2pub use funcs::WithFuncs;
3use std::collections::BTreeMap;
4use std::collections::HashMap;
5use std::path::PathBuf;
6use tparam::*;
7
8pub type TFunc = dyn for<'a> Fn(&[TCow<'a>]) -> anyhow::Result<TCow<'a>>;
9pub type TFn = for<'a> fn(&[TCow<'a>]) -> anyhow::Result<TCow<'a>>;
10
11pub trait FuncManager {
12    fn get_func(&self, k: &str) -> Option<&TFunc>;
13    fn for_each<F: Fn(&String, &str)>(&self, f: F);
14
15    fn print_all(&self) {
16        self.for_each(|k, v| {
17            print!("\n {}:", k);
18            for sp in v.split(":") {
19                println!("\t\t{}", sp);
20            }
21        })
22    }
23
24    fn print_filter(&self, s: &str) {
25        self.for_each(|k, v| {
26            if !k.contains(s) && !v.contains(s) {
27                return;
28            }
29            print!("\n {}:", k);
30            for sp in v.split(":") {
31                println!("\t\t{}", sp);
32            }
33        })
34    }
35}
36
37pub trait FuncAdder: Sized {
38    fn add_func<K: Into<String>>(&mut self, k: K, f: Box<TFunc>, description: &'static str);
39    fn add_fn<K: Into<String>>(&mut self, k: K, f: TFn, d: &'static str) {
40        self.add_func(k, Box::new(f), d);
41    }
42    fn with_func<K: Into<String>>(mut self, k: K, f: Box<TFunc>, d: &'static str) -> Self {
43        self.add_func(k, f, d);
44        self
45    }
46    fn with_fn<K: Into<String>>(mut self, k: K, f: TFn, d: &'static str) -> Self {
47        self.add_fn(k, f, d);
48        self
49    }
50}
51
52pub struct BasicFuncs {
53    funcs: HashMap<String, Box<TFunc>>,
54    descriptions: BTreeMap<String, &'static str>,
55}
56
57impl BasicFuncs {
58    pub fn new() -> Self {
59        BasicFuncs {
60            funcs: HashMap::new(),
61            descriptions: BTreeMap::new(),
62        }
63    }
64}
65
66impl FuncManager for BasicFuncs {
67    fn get_func(&self, k: &str) -> Option<&TFunc> {
68        self.funcs.get(k).map(|r| &**r)
69    }
70    fn for_each<F: Fn(&String, &str)>(&self, f: F) {
71        for (k, &v) in &self.descriptions {
72            f(k, v)
73        }
74    }
75}
76
77impl FuncAdder for BasicFuncs {
78    fn add_func<K: Into<String>>(&mut self, k: K, f: Box<TFunc>, description: &'static str) {
79        let ks: String = k.into();
80        self.funcs.insert(ks.clone(), f);
81        self.descriptions.insert(ks, description);
82    }
83}
84
85pub fn default_func_man() -> BasicFuncs {
86    BasicFuncs::new().with_defaults()
87}
88
89pub fn func_man_folders<P: Into<PathBuf>>(p: P) -> BasicFuncs {
90    BasicFuncs::new().with_defaults().with_folder_lock(p)
91}