1use serde_json::{Value, json};
29
30use crate::contract::{Contract, Resource};
31use crate::packed::WriteRefusal;
32
33pub const OUT_OF_RANGE: &str = "out_of_range";
36
37#[must_use]
40pub fn uses(c: &Contract, profile: &str) -> bool {
41 c.uses.iter().any(|u| u.to_string() == profile)
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
46pub enum Index {
47 At(u8),
49 OutOfRange,
51}
52
53impl Index {
54 #[must_use]
57 pub fn at(i: usize, max: u8) -> Index {
58 match u8::try_from(i) {
59 Ok(i) if i <= max => Index::At(i),
60 _ => Index::OutOfRange,
61 }
62 }
63
64 #[must_use]
66 pub fn to_json(self) -> Value {
67 match self {
68 Index::At(i) => json!(i),
69 Index::OutOfRange => json!(OUT_OF_RANGE),
70 }
71 }
72
73 pub fn of_json(v: &Value) -> Result<Index, WriteRefusal> {
79 match v {
80 Value::String(s) if s == OUT_OF_RANGE => Ok(Index::OutOfRange),
81 Value::Number(n) => n
82 .as_u64()
83 .and_then(|i| u8::try_from(i).ok())
84 .map(Index::At)
85 .ok_or(WriteRefusal::Range),
86 _ => Err(WriteRefusal::Value),
87 }
88 }
89}
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93pub enum Word<'a> {
94 Entry(&'a str),
96 Number(u8),
99 OutOfRange,
102}
103
104#[must_use]
106pub fn read<S: AsRef<str>>(table: Option<&[S]>, index: Index) -> Word<'_> {
107 match index {
108 Index::OutOfRange => Word::OutOfRange,
109 Index::At(i) => table
110 .and_then(|t| t.get(usize::from(i)))
111 .map_or(Word::Number(i), |w| Word::Entry(w.as_ref())),
112 }
113}
114
115#[must_use]
119pub fn write<S: AsRef<str>>(table: &[S], word: &str, max: u8) -> Index {
120 table
121 .iter()
122 .position(|w| w.as_ref() == word)
123 .map_or(Index::OutOfRange, |i| Index::at(i, max))
124}
125
126#[must_use]
130pub fn list(
131 v: &Value,
132 max: usize,
133 entry: impl Fn(&str) -> bool,
134 once: bool,
135) -> Option<Vec<String>> {
136 let a = v.as_array()?;
137 if a.len() > max {
138 return None;
139 }
140 let mut out: Vec<String> = Vec::with_capacity(a.len());
141 for x in a {
142 let x = x.as_str()?;
143 if !entry(x) || (once && out.iter().any(|seen| seen == x)) {
144 return None;
145 }
146 out.push(x.to_owned());
147 }
148 Some(out)
149}
150
151#[derive(Debug, Clone, PartialEq, Eq)]
154pub enum Instance<T> {
155 None,
157 Table(Vec<T>),
159 Differ,
161}
162
163impl<T> Instance<T> {
164 #[must_use]
166 pub fn table(&self) -> Option<&[T]> {
167 match self {
168 Instance::Table(t) => Some(t),
169 Instance::None | Instance::Differ => None,
170 }
171 }
172}
173
174#[must_use]
179pub fn instance_table<'a, T: PartialEq + Clone + 'a>(
180 named: impl IntoIterator<Item = Option<&'a [T]>>,
181) -> Instance<T> {
182 let mut held: Option<&[T]> = None;
183 for table in named.into_iter().flatten() {
184 match held {
185 None => held = Some(table),
186 Some(first) if first == table => {}
187 Some(_) => return Instance::Differ,
188 }
189 }
190 held.map_or(Instance::None, |t| Instance::Table(t.to_vec()))
191}
192
193#[derive(Debug, Clone, PartialEq, Eq)]
196pub struct Lint {
197 pub profile: &'static str,
199 pub at: String,
201 pub key: Option<&'static str>,
203 pub token: &'static str,
205 pub says: &'static str,
207}
208
209impl Lint {
210 #[must_use]
212 pub fn place(r: &Resource) -> String {
213 format!("{}/{}", r.token, r.template.as_str())
214 }
215}
216
217impl std::fmt::Display for Lint {
218 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
220 write!(f, "error[{} {}] {}: ", self.profile, self.token, self.at)?;
221 if let Some(key) = self.key {
222 write!(f, "{key}: ")?;
223 }
224 f.write_str(self.says)
225 }
226}
227
228#[cfg(test)]
229mod tests {
230 use super::*;
231
232 #[test]
233 fn an_index_reads_as_its_entry_its_number_or_out_of_range() {
234 let table = ["a".to_owned(), "b".to_owned()];
235 assert_eq!(read(Some(&table[..]), Index::At(1)), Word::Entry("b"));
236 assert_eq!(read(Some(&table[..]), Index::At(2)), Word::Number(2));
237 assert_eq!(read::<String>(None, Index::At(0)), Word::Number(0));
238 assert_eq!(read(Some(&table[..]), Index::OutOfRange), Word::OutOfRange);
239 assert_eq!(write(&table, "b", 254), Index::At(1));
240 assert_eq!(write(&table, "b", 0), Index::OutOfRange, "past the code");
241 assert_eq!(write(&table, "c", 254), Index::OutOfRange);
242 assert_eq!(Index::at(255, 254), Index::OutOfRange);
243 for i in [Index::At(7), Index::OutOfRange] {
244 assert_eq!(Index::of_json(&i.to_json()), Ok(i));
245 }
246 assert_eq!(Index::of_json(&json!(256)), Err(WriteRefusal::Range));
247 assert_eq!(Index::of_json(&json!("x")), Err(WriteRefusal::Value));
248 }
249
250 #[test]
251 fn an_instance_has_the_one_table_its_named_revisions_hold() {
252 let (a, b) = (vec![1, 2], vec![1, 3]);
253 assert_eq!(instance_table::<u8>([None, None]), Instance::None);
254 assert_eq!(
255 instance_table([Some(&a[..]), None, Some(&a[..])]),
256 Instance::Table(a.clone())
257 );
258 assert_eq!(
259 instance_table([Some(&a[..]), Some(&b[..])]),
260 Instance::Differ
261 );
262 assert_eq!(Instance::<u8>::Differ.table(), None);
263 assert_eq!(Instance::Table(a.clone()).table(), Some(&a[..]));
264 }
265
266 #[test]
267 fn a_list_is_a_table_within_its_bound_and_its_entries_rule() {
268 let v = json!(["a", "b", "a"]);
269 assert_eq!(list(&v, 3, |_| true, false).map(|t| t.len()), Some(3));
270 assert_eq!(list(&v, 3, |_| true, true), None, "one twice");
271 assert_eq!(list(&v, 2, |_| true, false), None, "one too many");
272 assert_eq!(list(&v, 3, |s| s != "b", false), None);
273 assert_eq!(list(&json!(["a", 1]), 3, |_| true, false), None);
274 assert_eq!(list(&json!("a"), 3, |_| true, false), None);
275 }
276}