use serde_json::{Value, json};
use crate::contract::{Contract, Resource};
use crate::packed::WriteRefusal;
pub const OUT_OF_RANGE: &str = "out_of_range";
#[must_use]
pub fn uses(c: &Contract, profile: &str) -> bool {
c.uses.iter().any(|u| u.to_string() == profile)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Index {
At(u8),
OutOfRange,
}
impl Index {
#[must_use]
pub fn at(i: usize, max: u8) -> Index {
match u8::try_from(i) {
Ok(i) if i <= max => Index::At(i),
_ => Index::OutOfRange,
}
}
#[must_use]
pub fn to_json(self) -> Value {
match self {
Index::At(i) => json!(i),
Index::OutOfRange => json!(OUT_OF_RANGE),
}
}
pub fn of_json(v: &Value) -> Result<Index, WriteRefusal> {
match v {
Value::String(s) if s == OUT_OF_RANGE => Ok(Index::OutOfRange),
Value::Number(n) => n
.as_u64()
.and_then(|i| u8::try_from(i).ok())
.map(Index::At)
.ok_or(WriteRefusal::Range),
_ => Err(WriteRefusal::Value),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Word<'a> {
Entry(&'a str),
Number(u8),
OutOfRange,
}
#[must_use]
pub fn read<S: AsRef<str>>(table: Option<&[S]>, index: Index) -> Word<'_> {
match index {
Index::OutOfRange => Word::OutOfRange,
Index::At(i) => table
.and_then(|t| t.get(usize::from(i)))
.map_or(Word::Number(i), |w| Word::Entry(w.as_ref())),
}
}
#[must_use]
pub fn write<S: AsRef<str>>(table: &[S], word: &str, max: u8) -> Index {
table
.iter()
.position(|w| w.as_ref() == word)
.map_or(Index::OutOfRange, |i| Index::at(i, max))
}
#[must_use]
pub fn list(
v: &Value,
max: usize,
entry: impl Fn(&str) -> bool,
once: bool,
) -> Option<Vec<String>> {
let a = v.as_array()?;
if a.len() > max {
return None;
}
let mut out: Vec<String> = Vec::with_capacity(a.len());
for x in a {
let x = x.as_str()?;
if !entry(x) || (once && out.iter().any(|seen| seen == x)) {
return None;
}
out.push(x.to_owned());
}
Some(out)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Instance<T> {
None,
Table(Vec<T>),
Differ,
}
impl<T> Instance<T> {
#[must_use]
pub fn table(&self) -> Option<&[T]> {
match self {
Instance::Table(t) => Some(t),
Instance::None | Instance::Differ => None,
}
}
}
#[must_use]
pub fn instance_table<'a, T: PartialEq + Clone + 'a>(
named: impl IntoIterator<Item = Option<&'a [T]>>,
) -> Instance<T> {
let mut held: Option<&[T]> = None;
for table in named.into_iter().flatten() {
match held {
None => held = Some(table),
Some(first) if first == table => {}
Some(_) => return Instance::Differ,
}
}
held.map_or(Instance::None, |t| Instance::Table(t.to_vec()))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Lint {
pub profile: &'static str,
pub at: String,
pub key: Option<&'static str>,
pub token: &'static str,
pub says: &'static str,
}
impl Lint {
#[must_use]
pub fn place(r: &Resource) -> String {
format!("{}/{}", r.token, r.template.as_str())
}
}
impl std::fmt::Display for Lint {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "error[{} {}] {}: ", self.profile, self.token, self.at)?;
if let Some(key) = self.key {
write!(f, "{key}: ")?;
}
f.write_str(self.says)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_index_reads_as_its_entry_its_number_or_out_of_range() {
let table = ["a".to_owned(), "b".to_owned()];
assert_eq!(read(Some(&table[..]), Index::At(1)), Word::Entry("b"));
assert_eq!(read(Some(&table[..]), Index::At(2)), Word::Number(2));
assert_eq!(read::<String>(None, Index::At(0)), Word::Number(0));
assert_eq!(read(Some(&table[..]), Index::OutOfRange), Word::OutOfRange);
assert_eq!(write(&table, "b", 254), Index::At(1));
assert_eq!(write(&table, "b", 0), Index::OutOfRange, "past the code");
assert_eq!(write(&table, "c", 254), Index::OutOfRange);
assert_eq!(Index::at(255, 254), Index::OutOfRange);
for i in [Index::At(7), Index::OutOfRange] {
assert_eq!(Index::of_json(&i.to_json()), Ok(i));
}
assert_eq!(Index::of_json(&json!(256)), Err(WriteRefusal::Range));
assert_eq!(Index::of_json(&json!("x")), Err(WriteRefusal::Value));
}
#[test]
fn an_instance_has_the_one_table_its_named_revisions_hold() {
let (a, b) = (vec![1, 2], vec![1, 3]);
assert_eq!(instance_table::<u8>([None, None]), Instance::None);
assert_eq!(
instance_table([Some(&a[..]), None, Some(&a[..])]),
Instance::Table(a.clone())
);
assert_eq!(
instance_table([Some(&a[..]), Some(&b[..])]),
Instance::Differ
);
assert_eq!(Instance::<u8>::Differ.table(), None);
assert_eq!(Instance::Table(a.clone()).table(), Some(&a[..]));
}
#[test]
fn a_list_is_a_table_within_its_bound_and_its_entries_rule() {
let v = json!(["a", "b", "a"]);
assert_eq!(list(&v, 3, |_| true, false).map(|t| t.len()), Some(3));
assert_eq!(list(&v, 3, |_| true, true), None, "one twice");
assert_eq!(list(&v, 2, |_| true, false), None, "one too many");
assert_eq!(list(&v, 3, |s| s != "b", false), None);
assert_eq!(list(&json!(["a", 1]), 3, |_| true, false), None);
assert_eq!(list(&json!("a"), 3, |_| true, false), None);
}
}