aboutsummaryrefslogtreecommitdiff
path: root/src/util/background/vars.rs
blob: fe54268ecd080258ebf2022b3b988b79aa4c93dd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
use std::collections::HashMap;
use std::str::FromStr;

use crate::error::{Error, OkOrMessage};
use crate::migrate::Migrate;
use crate::persister::PersisterShared;

pub struct BgVars {
	vars: HashMap<&'static str, Box<dyn BgVarTrait>>,
}

impl BgVars {
	pub fn new() -> Self {
		Self {
			vars: HashMap::new(),
		}
	}

	pub fn register_rw<V, T, GF, SF>(
		&mut self,
		p: &PersisterShared<V>,
		name: &'static str,
		get_fn: GF,
		set_fn: SF,
	) where
		V: Migrate + Default + Send + Sync,
		T: FromStr + ToString + Send + Sync + 'static,
		GF: Fn(&PersisterShared<V>) -> T + Send + Sync + 'static,
		SF: Fn(&PersisterShared<V>, T) -> Result<(), Error> + Send + Sync + 'static,
	{
		let p1 = p.clone();
		let get_fn = move || get_fn(&p1);

		let p2 = p.clone();
		let set_fn = move |v| set_fn(&p2, v);

		self.vars.insert(name, Box::new(BgVar { get_fn, set_fn }));
	}

	pub fn register_ro<V, T, GF>(&mut self, p: &PersisterShared<V>, name: &'static str, get_fn: GF)
	where
		V: Migrate + Default + Send + Sync,
		T: FromStr + ToString + Send + Sync + 'static,
		GF: Fn(&PersisterShared<V>) -> T + Send + Sync + 'static,
	{
		let p1 = p.clone();
		let get_fn = move || get_fn(&p1);

		let set_fn = move |_| Err(Error::Message(format!("Cannot set value of {}", name)));

		self.vars.insert(name, Box::new(BgVar { get_fn, set_fn }));
	}

	pub fn get(&self, var: &str) -> Result<String, Error> {
		Ok(self
			.vars
			.get(var)
			.ok_or_message("variable does not exist")?
			.get())
	}

	pub fn get_all(&self) -> Vec<(&'static str, String)> {
		self.vars.iter().map(|(k, v)| (*k, v.get())).collect()
	}

	pub fn set(&self, var: &str, val: &str) -> Result<(), Error> {
		self.vars
			.get(var)
			.ok_or_message("variable does not exist")?
			.set(val)
	}
}

// ----

trait BgVarTrait: Send + Sync + 'static {
	fn get(&self) -> String;
	fn set(&self, v: &str) -> Result<(), Error>;
}

struct BgVar<T, GF, SF>
where
	T: FromStr + ToString + Send + Sync + 'static,
	GF: Fn() -> T + Send + Sync + 'static,
	SF: Fn(T) -> Result<(), Error> + Sync + Send + 'static,
{
	get_fn: GF,
	set_fn: SF,
}

impl<T, GF, SF> BgVarTrait for BgVar<T, GF, SF>
where
	T: FromStr + ToString + Sync + Send + 'static,
	GF: Fn() -> T + Sync + Send + 'static,
	SF: Fn(T) -> Result<(), Error> + Sync + Send + 'static,
{
	fn get(&self) -> String {
		(self.get_fn)().to_string()
	}

	fn set(&self, vstr: &str) -> Result<(), Error> {
		let value = vstr
			.parse()
			.map_err(|_| Error::Message(format!("invalid value: {}", vstr)))?;
		(self.set_fn)(value)
	}
}