use serde::Serialize;
use serde_json::value::RawValue;
use super::event::Fields;
use crate::{Not, Prefix};
const MOST_VALUES: usize = 1000;
const MOST_VALUE_BYTES: usize = 4 << 10;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Condition(Result<Matching, String>);
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum Matching {
OneOf(Vec<String>),
NoneOf(Vec<String>),
Prefix(String),
}
impl Condition {
#[cfg(feature = "wire")]
pub(crate) fn exactly(json: String) -> Condition {
Condition(Ok(Matching::OneOf(vec![json])))
}
#[cfg(feature = "wire")]
pub(crate) fn listed(values: Vec<String>, not: bool) -> Condition {
Condition(Ok(if not { Matching::NoneOf(values) } else { Matching::OneOf(values) }))
}
#[cfg(feature = "wire")]
pub(crate) fn prefix(text: String) -> Condition {
Condition(Ok(Matching::Prefix(text)))
}
pub(super) fn checked(self, key: &str) -> Result<Matching, String> {
let refused = |why: String| format!("where {key:?}: {why}");
match self.0.map_err(refused)? {
Matching::OneOf(values) => Ok(Matching::OneOf(sorted(values).map_err(refused)?)),
Matching::NoneOf(values) => Ok(Matching::NoneOf(sorted(values).map_err(refused)?)),
Matching::Prefix(text) if text.is_empty() || text.len() > MOST_VALUE_BYTES => {
Err(refused(format!("a prefix of 1 to {MOST_VALUE_BYTES} bytes")))
}
Matching::Prefix(text) => Ok(Matching::Prefix(text)),
}
}
}
fn sorted(mut values: Vec<String>) -> Result<Vec<String>, String> {
if values.is_empty() || values.len() > MOST_VALUES {
let why = "a list or an object as the value itself goes in one, [[…]]";
return Err(format!("a list of 1 to {MOST_VALUES} values: {why}"));
}
if values.iter().any(|value| value.len() > MOST_VALUE_BYTES) {
return Err(format!("a value of {MOST_VALUE_BYTES} bytes at most"));
}
values.sort_unstable();
values.dedup();
Ok(values)
}
fn values_of(json: serde_json::Result<String>) -> Result<Vec<String>, String> {
let json = json.map_err(|error| format!("a value JSON cannot write: {error}"))?;
match json.as_bytes().first() {
Some(b'[') => {
let items: Vec<&RawValue> = serde_json::from_str(&json).map_err(|error| format!("a list: {error}"))?;
Ok(items.into_iter().map(|item| item.get().to_owned()).collect())
}
Some(b'{') => {
let why = "an object as the value itself goes in a list, [{…}]";
Err(format!("an object, where a value, a list, Not or Prefix goes: {why}"))
}
_ => Ok(vec![json]),
}
}
pub(super) fn among(values: &[String], json: &str) -> bool {
values.binary_search_by(|value| value.as_str().cmp(json)).is_ok()
}
impl<T: Serialize + ?Sized> From<&T> for Condition {
fn from(value: &T) -> Condition {
Condition(values_of(serde_json::to_string(value)).map(Matching::OneOf))
}
}
impl<T: Serialize> From<Not<T>> for Condition {
fn from(Not(value): Not<T>) -> Condition {
Condition(values_of(serde_json::to_string(&value)).map(Matching::NoneOf))
}
}
impl<T: Into<String>> From<Prefix<T>> for Condition {
fn from(Prefix(text): Prefix<T>) -> Condition {
Condition(Ok(Matching::Prefix(text.into())))
}
}
impl Matching {
pub(super) fn finds(&self, key: &str, fields: &Fields, context: &Fields) -> bool {
let (field, held) = (fields.json(key), context.json(key));
match self {
Matching::OneOf(_) => self.holds(field) || self.holds(held),
Matching::NoneOf(_) => !self.holds(field) && !self.holds(held),
Matching::Prefix(_) => self.holds(field) || self.holds(held),
}
}
pub(super) fn holds(&self, json: Option<&str>) -> bool {
let Some(json) = json else { return false };
match self {
Matching::OneOf(values) | Matching::NoneOf(values) => among(values, json),
Matching::Prefix(prefix) => {
json.starts_with('"') && serde_json::from_str::<String>(json).is_ok_and(|text| text.starts_with(prefix))
}
}
}
pub(super) fn one_of(&self) -> Option<&[String]> {
match self {
Matching::OneOf(values) => Some(values),
Matching::NoneOf(_) | Matching::Prefix(_) => None,
}
}
pub(super) fn needs_key(&self) -> bool {
!matches!(self, Matching::NoneOf(_))
}
}