1use std::collections::BTreeMap;
8
9use schemars::JsonSchema;
10use serde::{Deserialize, Serialize};
11use serde_json::Value;
12
13#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
15#[serde(tag = "kind", rename_all = "snake_case")]
16pub enum ParamKind {
17 Number {
19 #[serde(default, skip_serializing_if = "Option::is_none")]
20 min: Option<f64>,
21 #[serde(default, skip_serializing_if = "Option::is_none")]
22 max: Option<f64>,
23 #[serde(default, skip_serializing_if = "Option::is_none")]
24 unit: Option<String>,
25 },
26 Integer {
28 #[serde(default, skip_serializing_if = "Option::is_none")]
29 min: Option<i64>,
30 #[serde(default, skip_serializing_if = "Option::is_none")]
31 max: Option<i64>,
32 },
33 Switch,
35 Text,
37 Choice {
39 options: Vec<String>,
41 },
42}
43
44#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
46#[serde(untagged)]
47pub enum ParamValue {
48 Switch(bool),
50 Integer(i64),
52 Number(f64),
54 Text(String),
56}
57
58impl ParamValue {
59 pub fn as_f64(&self) -> Option<f64> {
61 match self {
62 ParamValue::Number(v) => Some(*v),
63 ParamValue::Integer(v) => Some(*v as f64),
64 _ => None,
65 }
66 }
67
68 pub fn to_json(&self) -> Value {
70 serde_json::to_value(self).unwrap_or(Value::Null)
71 }
72
73 pub fn from_json(v: &Value) -> Option<ParamValue> {
75 serde_json::from_value(v.clone()).ok()
76 }
77}
78
79#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
81pub struct ParamSpec {
82 pub name: String,
84 #[serde(flatten)]
86 pub kind: ParamKind,
87 pub default: ParamValue,
89 #[serde(default, skip_serializing_if = "String::is_empty")]
91 pub hint: String,
92}
93
94impl ParamSpec {
95 pub fn number(name: impl Into<String>, default: f64) -> Self {
97 Self {
98 name: name.into(),
99 kind: ParamKind::Number { min: None, max: None, unit: None },
100 default: ParamValue::Number(default),
101 hint: String::new(),
102 }
103 }
104
105 pub fn integer(name: impl Into<String>, default: i64) -> Self {
107 Self {
108 name: name.into(),
109 kind: ParamKind::Integer { min: None, max: None },
110 default: ParamValue::Integer(default),
111 hint: String::new(),
112 }
113 }
114
115 pub fn switch(name: impl Into<String>, default: bool) -> Self {
117 Self { name: name.into(), kind: ParamKind::Switch, default: ParamValue::Switch(default), hint: String::new() }
118 }
119
120 pub fn text(name: impl Into<String>, default: impl Into<String>) -> Self {
122 Self {
123 name: name.into(),
124 kind: ParamKind::Text,
125 default: ParamValue::Text(default.into()),
126 hint: String::new(),
127 }
128 }
129
130 pub fn choice(name: impl Into<String>, options: &[&str]) -> Self {
132 let options: Vec<String> = options.iter().map(|s| s.to_string()).collect();
133 let default = ParamValue::Text(options.first().cloned().unwrap_or_default());
134 Self { name: name.into(), kind: ParamKind::Choice { options }, default, hint: String::new() }
135 }
136
137 pub fn range(mut self, lo: f64, hi: f64) -> Self {
139 match &mut self.kind {
140 ParamKind::Number { min, max, .. } => {
141 *min = Some(lo);
142 *max = Some(hi);
143 }
144 ParamKind::Integer { min, max } => {
145 *min = Some(lo as i64);
146 *max = Some(hi as i64);
147 }
148 _ => {}
149 }
150 self
151 }
152
153 pub fn unit(mut self, u: impl Into<String>) -> Self {
155 if let ParamKind::Number { unit, .. } = &mut self.kind {
156 *unit = Some(u.into());
157 }
158 self
159 }
160
161 pub fn hint(mut self, hint: impl Into<String>) -> Self {
163 self.hint = hint.into();
164 self
165 }
166
167 pub fn check(&self, value: &ParamValue) -> Result<ParamValue, String> {
170 let name = &self.name;
171 match (&self.kind, value) {
172 (ParamKind::Number { min, max, .. }, v) => {
173 let x = v.as_f64().ok_or_else(|| format!("{name} is a number"))?;
174 if !x.is_finite() {
175 return Err(format!("{name} is a finite number"));
176 }
177 if let Some(lo) = min.filter(|lo| x < *lo) {
178 return Err(format!("{name} is at least {lo} (got {x})"));
179 }
180 if let Some(hi) = max.filter(|hi| x > *hi) {
181 return Err(format!("{name} is at most {hi} (got {x})"));
182 }
183 Ok(ParamValue::Number(x))
184 }
185 (ParamKind::Integer { min, max }, v) => {
186 let x = match v {
187 ParamValue::Integer(i) => *i,
188 ParamValue::Number(f) if f.fract() == 0.0 && f.is_finite() => *f as i64,
189 _ => return Err(format!("{name} is a whole number")),
190 };
191 if let Some(lo) = min.filter(|lo| x < *lo) {
192 return Err(format!("{name} is at least {lo} (got {x})"));
193 }
194 if let Some(hi) = max.filter(|hi| x > *hi) {
195 return Err(format!("{name} is at most {hi} (got {x})"));
196 }
197 Ok(ParamValue::Integer(x))
198 }
199 (ParamKind::Switch, ParamValue::Switch(b)) => Ok(ParamValue::Switch(*b)),
200 (ParamKind::Switch, _) => Err(format!("{name} is on or off (true or false)")),
201 (ParamKind::Text, ParamValue::Text(t)) => Ok(ParamValue::Text(t.clone())),
202 (ParamKind::Text, _) => Err(format!("{name} is text")),
203 (ParamKind::Choice { options }, ParamValue::Text(t)) if options.contains(t) => {
204 Ok(ParamValue::Text(t.clone()))
205 }
206 (ParamKind::Choice { options }, _) => Err(format!("{name} is one of {}", options.join(", "))),
207 }
208 }
209}
210
211pub fn check_params(
214 specs: &[ParamSpec],
215 given: &BTreeMap<String, ParamValue>,
216) -> Result<BTreeMap<String, ParamValue>, Vec<String>> {
217 let mut out = BTreeMap::new();
218 let mut problems = Vec::new();
219 for spec in specs {
220 match given.get(&spec.name) {
221 Some(v) => match spec.check(v) {
222 Ok(v) => {
223 out.insert(spec.name.clone(), v);
224 }
225 Err(e) => problems.push(e),
226 },
227 None => {
228 out.insert(spec.name.clone(), spec.default.clone());
229 }
230 }
231 }
232 for name in given.keys().filter(|n| !specs.iter().any(|s| &s.name == *n)) {
233 problems.push(format!("no parameter {name}"));
234 }
235 if problems.is_empty() { Ok(out) } else { Err(problems) }
236}
237
238#[cfg(test)]
239mod tests {
240 use super::*;
241
242 #[test]
243 fn params_are_checked_and_filled() {
244 let specs = vec![
245 ParamSpec::number("sigma", 2.0).range(0.2, 20.0).unit("px"),
246 ParamSpec::integer("bins", 256).range(2.0, 4096.0),
247 ParamSpec::switch("invert", false),
248 ParamSpec::choice("band", &["highpass", "lowpass"]),
249 ];
250 let given: BTreeMap<String, ParamValue> =
251 [("sigma".to_string(), ParamValue::Integer(3)), ("band".to_string(), ParamValue::Text("lowpass".into()))]
252 .into();
253 let full = check_params(&specs, &given).unwrap();
254 assert_eq!(full["sigma"], ParamValue::Number(3.0), "a whole number given for a number");
255 assert_eq!(full["bins"], ParamValue::Integer(256), "the default");
256 assert_eq!(full["band"], ParamValue::Text("lowpass".into()));
257 let bad: BTreeMap<String, ParamValue> = [
258 ("sigma".to_string(), ParamValue::Number(50.0)),
259 ("bins".to_string(), ParamValue::Number(2.5)),
260 ("band".to_string(), ParamValue::Text("notch".into())),
261 ("gamma".to_string(), ParamValue::Number(1.0)),
262 ]
263 .into();
264 let problems = check_params(&specs, &bad).unwrap_err();
265 assert_eq!(problems.len(), 4, "{problems:?}");
266 assert!(problems.iter().any(|p| p.contains("at most 20")));
267 assert!(problems.iter().any(|p| p.contains("no parameter gamma")));
268 }
269
270 #[test]
271 fn values_read_from_json() {
272 let v: Vec<ParamValue> = serde_json::from_str(r#"[true, 3, 2.5, "x"]"#).unwrap();
273 assert_eq!(
274 v,
275 [ParamValue::Switch(true), ParamValue::Integer(3), ParamValue::Number(2.5), ParamValue::Text("x".into())]
276 );
277 let spec: ParamSpec =
278 serde_json::from_str(r#"{"name":"sigma","kind":"number","min":0.2,"default":2.0}"#).unwrap();
279 assert_eq!(spec.kind, ParamKind::Number { min: Some(0.2), max: None, unit: None });
280 }
281}