use core::fmt;
pub enum Predicate {
Uuid,
IntInRange(i64, i64),
F64InRange(f64, f64),
F64Any,
NonEmpty,
AnyText,
}
impl Predicate {
pub fn test(&self, value: &str) -> Result<(), String> {
match self {
Predicate::Uuid => {
let parts: Vec<&str> = value.split('-').collect();
let ok = parts.len() == 5
&& [8usize, 4, 4, 4, 12]
== [
parts[0].len(),
parts[1].len(),
parts[2].len(),
parts[3].len(),
parts[4].len(),
]
&& parts
.iter()
.all(|p| p.chars().all(|c| c.is_ascii_hexdigit()));
if ok {
Ok(())
} else {
Err(format!("{value:?} is not a UID of the shape 8-4-4-4-12"))
}
}
Predicate::IntInRange(lo, hi) => match value.trim().parse::<i64>() {
Ok(v) if v >= *lo && v <= *hi => Ok(()),
Ok(v) => Err(format!("{v} is outside {lo} to {hi}")),
Err(_) => Err(format!("{value:?} is not an integer")),
},
Predicate::F64InRange(lo, hi) => match value.trim().parse::<f64>() {
Ok(v) if v >= *lo && v <= *hi => Ok(()),
Ok(v) => Err(format!("{v} is outside {lo} to {hi}")),
Err(_) => Err(format!("{value:?} is not a real number")),
},
Predicate::F64Any => match value.trim().parse::<f64>() {
Ok(_) => Ok(()),
Err(_) => Err(format!("{value:?} is not a real number")),
},
Predicate::NonEmpty => {
if value.trim().is_empty() {
Err("the value is empty".to_string())
} else {
Ok(())
}
}
Predicate::AnyText => Ok(()),
}
}
}
pub struct Rule {
pub field: &'static str,
pub placeholder: &'static str,
pub predicate: Predicate,
pub reason: &'static str,
}
pub fn feed_rules() -> Vec<Rule> {
vec![
Rule {
field: "uid",
placeholder: "<UID>",
predicate: Predicate::Uuid,
reason: "a stream instance identifier is random, and it changes on every restart",
},
Rule {
field: "endian-performance",
placeholder: "<PERF>",
predicate: Predicate::F64Any,
reason: "a measured benchmark result. SPEC.md 5.2 records it as observed",
},
Rule {
field: "hostname",
placeholder: "<HOST>",
predicate: Predicate::AnyText,
reason: "a property of the machine. An empty value is legal",
},
Rule {
field: "source-id",
placeholder: "<SOURCE>",
predicate: Predicate::AnyText,
reason: "chosen by the application. An empty value is legal",
},
]
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Erased {
pub field: String,
pub value: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Canonical {
pub text: String,
pub erased: Vec<Erased>,
}
impl fmt::Display for Canonical {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.text)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Violation {
pub field: String,
pub value: String,
pub problem: String,
}
pub fn canonicalize(block: &str, rules: &[Rule]) -> Canonical {
let mut out = String::with_capacity(block.len());
let mut erased = Vec::new();
for line in block.split_inclusive('\n') {
let body = line.trim_end_matches(['\r', '\n']);
let mut replaced = false;
if let Some(colon) = body.find(':') {
let name = body[..colon].trim().to_ascii_lowercase();
if let Some(rule) = rules.iter().find(|r| r.field == name) {
let value = body[colon + 1..].trim().to_string();
erased.push(Erased { field: name, value });
out.push_str(&body[..colon + 1]);
out.push(' ');
out.push_str(rule.placeholder);
out.push_str("\r\n");
replaced = true;
}
}
if !replaced {
out.push_str(body);
out.push_str("\r\n");
}
}
Canonical { text: out, erased }
}
pub fn check(canonical: &Canonical, rules: &[Rule]) -> Vec<Violation> {
let mut out = Vec::new();
for e in &canonical.erased {
let rule = match rules.iter().find(|r| r.field == e.field) {
Some(r) => r,
None => continue,
};
if let Err(problem) = rule.predicate.test(&e.value) {
out.push(Violation {
field: e.field.clone(),
value: e.value.clone(),
problem,
});
}
}
out
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LintFailure {
pub field: String,
pub problem: String,
}
pub fn lint(rules: &[Rule]) -> Vec<LintFailure> {
let mut out = Vec::new();
for r in rules {
if r.reason.trim().is_empty() {
out.push(LintFailure {
field: r.field.to_string(),
problem: "the rule gives no reason".into(),
});
}
if r.placeholder.trim().is_empty() {
out.push(LintFailure {
field: r.field.to_string(),
problem: "the rule gives no placeholder".into(),
});
}
if matches!(r.predicate, Predicate::AnyText) && r.reason.len() < 20 {
out.push(LintFailure {
field: r.field.to_string(),
problem: "a rule that asserts nothing needs a reason that explains why".into(),
});
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
const ANSWER: &str = "LSL/110 200 OK\r\nUID: 0b4645ec-dd4b-4582-a256-36119e117403\r\n\
Byte-Order: 1234\r\nSuppress-Subnormals: 0\r\nData-Protocol-Version: 110\r\n\r\n";
#[test]
fn every_rule_passes_the_lint() {
let failures = lint(&feed_rules());
assert!(failures.is_empty(), "the rules fail the lint: {failures:?}");
}
#[test]
fn a_rule_with_no_reason_fails_the_lint() {
let bad = vec![Rule {
field: "uid",
placeholder: "<UID>",
predicate: Predicate::Uuid,
reason: "",
}];
assert_eq!(lint(&bad).len(), 1);
}
#[test]
fn a_rule_that_asserts_nothing_needs_a_full_reason() {
let bad = vec![Rule {
field: "hostname",
placeholder: "<HOST>",
predicate: Predicate::AnyText,
reason: "varies",
}];
assert_eq!(lint(&bad).len(), 1);
}
#[test]
fn the_uid_is_replaced_and_the_rest_stays() {
let c = canonicalize(ANSWER, &feed_rules());
assert!(c.text.contains("UID: <UID>"));
assert!(c.text.contains("Byte-Order: 1234"));
assert!(c.text.contains("Data-Protocol-Version: 110"));
assert_eq!(c.erased.len(), 1);
assert_eq!(c.erased[0].value, "0b4645ec-dd4b-4582-a256-36119e117403");
}
#[test]
fn two_answers_with_different_uids_agree_after_canonicalizing() {
let other = ANSWER.replace(
"0b4645ec-dd4b-4582-a256-36119e117403",
"25cfa701-e55b-4e42-8fc2-103bbd2f86b6",
);
assert_eq!(
canonicalize(ANSWER, &feed_rules()).text,
canonicalize(&other, &feed_rules()).text
);
}
#[test]
fn the_predicate_catches_a_uid_of_the_wrong_shape() {
let bad = ANSWER.replace("0b4645ec-dd4b-4582-a256-36119e117403", "not-a-uid");
let c = canonicalize(&bad, &feed_rules());
let v = check(&c, &feed_rules());
assert_eq!(v.len(), 1);
assert_eq!(v[0].field, "uid");
}
#[test]
fn a_good_answer_raises_no_violation() {
let c = canonicalize(ANSWER, &feed_rules());
assert!(check(&c, &feed_rules()).is_empty());
}
#[test]
fn a_measured_value_must_still_parse() {
let rules = feed_rules();
let good = canonicalize("Endian-Performance: 12345\r\n", &rules);
assert!(check(&good, &rules).is_empty());
let bad = canonicalize("Endian-Performance: fast\r\n", &rules);
assert_eq!(check(&bad, &rules).len(), 1);
}
#[test]
fn a_stable_field_is_never_erased() {
let c = canonicalize(ANSWER, &feed_rules());
assert!(!c.erased.iter().any(|e| e.field == "byte-order"));
let changed = ANSWER.replace("Byte-Order: 1234", "Byte-Order: 4321");
assert_ne!(c.text, canonicalize(&changed, &feed_rules()).text);
}
}