1use core::fmt;
14
15pub enum Predicate {
17 Uuid,
19 IntInRange(i64, i64),
21 F64InRange(f64, f64),
23 F64Any,
28 NonEmpty,
30 AnyText,
35}
36
37impl Predicate {
38 pub fn test(&self, value: &str) -> Result<(), String> {
40 match self {
41 Predicate::Uuid => {
42 let parts: Vec<&str> = value.split('-').collect();
43 let ok = parts.len() == 5
44 && [8usize, 4, 4, 4, 12]
45 == [
46 parts[0].len(),
47 parts[1].len(),
48 parts[2].len(),
49 parts[3].len(),
50 parts[4].len(),
51 ]
52 && parts
53 .iter()
54 .all(|p| p.chars().all(|c| c.is_ascii_hexdigit()));
55 if ok {
56 Ok(())
57 } else {
58 Err(format!("{value:?} is not a UID of the shape 8-4-4-4-12"))
59 }
60 }
61 Predicate::IntInRange(lo, hi) => match value.trim().parse::<i64>() {
62 Ok(v) if v >= *lo && v <= *hi => Ok(()),
63 Ok(v) => Err(format!("{v} is outside {lo} to {hi}")),
64 Err(_) => Err(format!("{value:?} is not an integer")),
65 },
66 Predicate::F64InRange(lo, hi) => match value.trim().parse::<f64>() {
67 Ok(v) if v >= *lo && v <= *hi => Ok(()),
68 Ok(v) => Err(format!("{v} is outside {lo} to {hi}")),
69 Err(_) => Err(format!("{value:?} is not a real number")),
70 },
71 Predicate::F64Any => match value.trim().parse::<f64>() {
72 Ok(_) => Ok(()),
73 Err(_) => Err(format!("{value:?} is not a real number")),
74 },
75 Predicate::NonEmpty => {
76 if value.trim().is_empty() {
77 Err("the value is empty".to_string())
78 } else {
79 Ok(())
80 }
81 }
82 Predicate::AnyText => Ok(()),
83 }
84 }
85}
86
87pub struct Rule {
89 pub field: &'static str,
91 pub placeholder: &'static str,
93 pub predicate: Predicate,
95 pub reason: &'static str,
97}
98
99pub fn feed_rules() -> Vec<Rule> {
104 vec![
105 Rule {
106 field: "uid",
107 placeholder: "<UID>",
108 predicate: Predicate::Uuid,
109 reason: "a stream instance identifier is random, and it changes on every restart",
110 },
111 Rule {
112 field: "endian-performance",
113 placeholder: "<PERF>",
114 predicate: Predicate::F64Any,
115 reason: "a measured benchmark result. SPEC.md 5.2 records it as observed",
116 },
117 Rule {
118 field: "hostname",
119 placeholder: "<HOST>",
120 predicate: Predicate::AnyText,
121 reason: "a property of the machine. An empty value is legal",
122 },
123 Rule {
124 field: "source-id",
125 placeholder: "<SOURCE>",
126 predicate: Predicate::AnyText,
127 reason: "chosen by the application. An empty value is legal",
128 },
129 ]
130}
131
132#[derive(Debug, Clone, PartialEq, Eq)]
134pub struct Erased {
135 pub field: String,
137 pub value: String,
139}
140
141#[derive(Debug, Clone, PartialEq, Eq)]
143pub struct Canonical {
144 pub text: String,
146 pub erased: Vec<Erased>,
148}
149
150impl fmt::Display for Canonical {
151 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152 write!(f, "{}", self.text)
153 }
154}
155
156#[derive(Debug, Clone, PartialEq, Eq)]
158pub struct Violation {
159 pub field: String,
161 pub value: String,
163 pub problem: String,
165}
166
167pub fn canonicalize(block: &str, rules: &[Rule]) -> Canonical {
172 let mut out = String::with_capacity(block.len());
173 let mut erased = Vec::new();
174
175 for line in block.split_inclusive('\n') {
176 let body = line.trim_end_matches(['\r', '\n']);
177 let mut replaced = false;
178
179 if let Some(colon) = body.find(':') {
180 let name = body[..colon].trim().to_ascii_lowercase();
181 if let Some(rule) = rules.iter().find(|r| r.field == name) {
182 let value = body[colon + 1..].trim().to_string();
183 erased.push(Erased { field: name, value });
184 out.push_str(&body[..colon + 1]);
185 out.push(' ');
186 out.push_str(rule.placeholder);
187 out.push_str("\r\n");
188 replaced = true;
189 }
190 }
191 if !replaced {
192 out.push_str(body);
193 out.push_str("\r\n");
194 }
195 }
196 Canonical { text: out, erased }
197}
198
199pub fn check(canonical: &Canonical, rules: &[Rule]) -> Vec<Violation> {
204 let mut out = Vec::new();
205 for e in &canonical.erased {
206 let rule = match rules.iter().find(|r| r.field == e.field) {
207 Some(r) => r,
208 None => continue,
209 };
210 if let Err(problem) = rule.predicate.test(&e.value) {
211 out.push(Violation {
212 field: e.field.clone(),
213 value: e.value.clone(),
214 problem,
215 });
216 }
217 }
218 out
219}
220
221#[derive(Debug, Clone, PartialEq, Eq)]
223pub struct LintFailure {
224 pub field: String,
226 pub problem: String,
228}
229
230pub fn lint(rules: &[Rule]) -> Vec<LintFailure> {
239 let mut out = Vec::new();
240 for r in rules {
241 if r.reason.trim().is_empty() {
242 out.push(LintFailure {
243 field: r.field.to_string(),
244 problem: "the rule gives no reason".into(),
245 });
246 }
247 if r.placeholder.trim().is_empty() {
248 out.push(LintFailure {
249 field: r.field.to_string(),
250 problem: "the rule gives no placeholder".into(),
251 });
252 }
253 if matches!(r.predicate, Predicate::AnyText) && r.reason.len() < 20 {
254 out.push(LintFailure {
255 field: r.field.to_string(),
256 problem: "a rule that asserts nothing needs a reason that explains why".into(),
257 });
258 }
259 }
260 out
261}
262
263#[cfg(test)]
264mod tests {
265 use super::*;
266
267 const ANSWER: &str = "LSL/110 200 OK\r\nUID: 0b4645ec-dd4b-4582-a256-36119e117403\r\n\
268 Byte-Order: 1234\r\nSuppress-Subnormals: 0\r\nData-Protocol-Version: 110\r\n\r\n";
269
270 #[test]
271 fn every_rule_passes_the_lint() {
272 let failures = lint(&feed_rules());
273 assert!(failures.is_empty(), "the rules fail the lint: {failures:?}");
274 }
275
276 #[test]
277 fn a_rule_with_no_reason_fails_the_lint() {
278 let bad = vec![Rule {
279 field: "uid",
280 placeholder: "<UID>",
281 predicate: Predicate::Uuid,
282 reason: "",
283 }];
284 assert_eq!(lint(&bad).len(), 1);
285 }
286
287 #[test]
288 fn a_rule_that_asserts_nothing_needs_a_full_reason() {
289 let bad = vec![Rule {
290 field: "hostname",
291 placeholder: "<HOST>",
292 predicate: Predicate::AnyText,
293 reason: "varies",
294 }];
295 assert_eq!(lint(&bad).len(), 1);
296 }
297
298 #[test]
299 fn the_uid_is_replaced_and_the_rest_stays() {
300 let c = canonicalize(ANSWER, &feed_rules());
301 assert!(c.text.contains("UID: <UID>"));
302 assert!(c.text.contains("Byte-Order: 1234"));
303 assert!(c.text.contains("Data-Protocol-Version: 110"));
304 assert_eq!(c.erased.len(), 1);
305 assert_eq!(c.erased[0].value, "0b4645ec-dd4b-4582-a256-36119e117403");
306 }
307
308 #[test]
309 fn two_answers_with_different_uids_agree_after_canonicalizing() {
310 let other = ANSWER.replace(
311 "0b4645ec-dd4b-4582-a256-36119e117403",
312 "25cfa701-e55b-4e42-8fc2-103bbd2f86b6",
313 );
314 assert_eq!(
315 canonicalize(ANSWER, &feed_rules()).text,
316 canonicalize(&other, &feed_rules()).text
317 );
318 }
319
320 #[test]
321 fn the_predicate_catches_a_uid_of_the_wrong_shape() {
322 let bad = ANSWER.replace("0b4645ec-dd4b-4582-a256-36119e117403", "not-a-uid");
323 let c = canonicalize(&bad, &feed_rules());
324 let v = check(&c, &feed_rules());
325 assert_eq!(v.len(), 1);
326 assert_eq!(v[0].field, "uid");
327 }
328
329 #[test]
330 fn a_good_answer_raises_no_violation() {
331 let c = canonicalize(ANSWER, &feed_rules());
332 assert!(check(&c, &feed_rules()).is_empty());
333 }
334
335 #[test]
336 fn a_measured_value_must_still_parse() {
337 let rules = feed_rules();
338 let good = canonicalize("Endian-Performance: 12345\r\n", &rules);
339 assert!(check(&good, &rules).is_empty());
340 let bad = canonicalize("Endian-Performance: fast\r\n", &rules);
341 assert_eq!(check(&bad, &rules).len(), 1);
342 }
343
344 #[test]
345 fn a_stable_field_is_never_erased() {
346 let c = canonicalize(ANSWER, &feed_rules());
349 assert!(!c.erased.iter().any(|e| e.field == "byte-order"));
350 let changed = ANSWER.replace("Byte-Order: 1234", "Byte-Order: 4321");
351 assert_ne!(c.text, canonicalize(&changed, &feed_rules()).text);
352 }
353}