hyprstream_bench/gen/
jsoncheck.rs1use hyprstream_decision::Entry;
7
8use crate::family::{Family, Stratum};
9use crate::gen::stream;
10use crate::item::Item;
11
12const FAMILY: Family = Family::JsonCheck;
13
14struct Doc {
15 text: String,
16 valid: bool,
17 errors: usize,
19 repair: usize,
23}
24
25fn document(seed: u64, stratum: Stratum) -> Doc {
26 let mut rng = stream(seed);
27 let key = ["name", "port", "zone", "owner", "quota"][rng.below(5) as usize];
28 let value = rng.range(1, 9999);
29 let host = format!("srv-{}", rng.range(1, 99));
30 let clean = format!("{{\"{key}\": {value}, \"host\": \"{host}\"}}");
31 if stratum != Stratum::NearMiss {
32 return Doc {
33 text: clean,
34 valid: true,
35 errors: 0,
36 repair: 4,
37 };
38 }
39 let variant = rng.below(5);
42 let (text, errors) = match variant {
43 0 => (format!("{{\"{key}\": {value}, \"host\": \"{host}\",}}"), 1), 1 => (format!("{{{key}: {value}, \"host\": \"{host}\"}}"), 1), 2 => (format!("{{\"{key}\": {value}, \"host\": '{host}'}}"), 1), 3 => (format!("{{\"{key}\": {value}, \"host\": \"{host}\""), 1), _ => (clean, 0),
48 };
49 let valid = errors == 0;
50 debug_assert_eq!(
51 valid,
52 serde_json::from_str::<serde_json::Value>(&text).is_ok()
53 );
54 Doc {
55 text,
56 valid,
57 errors,
58 repair: if valid { 4 } else { variant as usize },
59 }
60}
61
62pub fn noul(seed: u64, stratum: Stratum) -> Item {
63 let doc = document(seed, stratum);
64 Item::noul(
65 FAMILY,
66 stratum,
67 seed,
68 Entry::Str(doc.text),
69 "Is the state a syntactically valid JSON document?",
70 doc.valid,
71 )
72}
73
74pub fn choice(seed: u64, stratum: Stratum) -> Item {
75 let mut rng = stream(seed ^ 0xC0);
76 let doc = document(seed, stratum);
77 let options = [
78 "remove the trailing comma",
79 "quote the bare object key",
80 "replace single quotes with double quotes",
81 "add the missing closing brace",
82 "the document is already valid",
83 ];
84 let correct = doc.repair;
87 let order = rng.permutation(options.len());
89 let shuffled: Vec<String> = order.iter().map(|&i| options[i].to_owned()).collect();
90 let new_correct = order
91 .iter()
92 .position(|&i| i == correct)
93 .unwrap_or_else(|| unreachable!("permutation contains every index"));
94 let _ = rng;
95 Item::choice(
96 FAMILY,
97 stratum,
98 seed,
99 Entry::Str(doc.text),
100 "Which single repair makes the state a valid JSON document?",
101 shuffled,
102 new_correct,
103 )
104}
105
106pub fn score(seed: u64, stratum: Stratum) -> Item {
107 let doc = document(seed, stratum);
108 Item::score(
109 FAMILY,
110 stratum,
111 seed,
112 Entry::Str(doc.text),
113 "How many JSON syntax errors does the state contain? Levels: 0 = none, 1 = one or more.",
114 2,
115 doc.errors.min(1),
116 )
117}