use std::fmt;
use std::time::Duration;
#[derive(Debug, Clone, PartialEq)]
pub struct Filter {
pub expression: Option<Expression>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Expression {
And(Vec<Expression>),
Sequence(Vec<Expression>),
Or(Vec<Expression>),
Not(Box<Expression>),
Restriction(Restriction),
Global(Comparable),
}
#[derive(Debug, Clone, PartialEq)]
pub struct Restriction {
pub comparable: Comparable,
pub comparator: Comparator,
pub arg: Arg,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Comparator {
Equal,
NotEqual,
GreaterThan,
GreaterThanOrEqual,
LessThan,
LessThanOrEqual,
Has,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Comparable {
Member(Member),
Function(Function),
}
#[derive(Debug, Clone, PartialEq)]
pub struct Member {
pub value: Value,
pub fields: Vec<Value>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Function {
pub name: Vec<String>,
pub args: Vec<Arg>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Arg {
Comparable(Comparable),
Composite(Box<Expression>),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Value {
Text(String),
String(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StringMatch<'a> {
Exact(&'a str),
Prefix(&'a str),
Suffix(&'a str),
Contains(&'a str),
}
impl Filter {
pub fn is_empty(&self) -> bool {
self.expression.is_none()
}
}
impl Comparable {
pub fn as_member(&self) -> Option<&Member> {
match self {
Comparable::Member(member) => Some(member),
Comparable::Function(_) => None,
}
}
pub fn field_path(&self) -> Option<String> {
self.as_member().and_then(Member::field_path)
}
}
impl Member {
pub fn is_simple(&self) -> bool {
self.fields.is_empty()
}
pub fn field_path(&self) -> Option<String> {
let mut path = String::new();
for (index, segment) in std::iter::once(&self.value).chain(&self.fields).enumerate() {
let Value::Text(text) = segment else {
return None;
};
if index > 0 {
path.push('.');
}
path.push_str(text);
}
Some(path)
}
}
impl Arg {
pub fn as_value(&self) -> Option<&Value> {
match self {
Arg::Comparable(Comparable::Member(member)) if member.is_simple() => {
Some(&member.value)
}
_ => None,
}
}
}
impl Value {
pub fn as_str(&self) -> &str {
match self {
Value::Text(text) | Value::String(text) => text,
}
}
pub fn is_quoted(&self) -> bool {
matches!(self, Value::String(_))
}
pub fn as_bool(&self) -> Option<bool> {
match self {
Value::Text(text) if text == "true" => Some(true),
Value::Text(text) if text == "false" => Some(false),
_ => None,
}
}
pub fn as_i64(&self) -> Option<i64> {
match self {
Value::Text(text) => text.parse().ok(),
Value::String(_) => None,
}
}
pub fn as_u64(&self) -> Option<u64> {
match self {
Value::Text(text) => text.parse().ok(),
Value::String(_) => None,
}
}
pub fn as_f64(&self) -> Option<f64> {
match self {
Value::Text(text) if is_decimal_number(text) => {
text.parse().ok().filter(|n: &f64| n.is_finite())
}
_ => None,
}
}
pub fn is_null(&self) -> bool {
matches!(self, Value::Text(text) if text == "null")
}
pub fn as_duration(&self) -> Option<Duration> {
let Value::Text(text) = self else {
return None;
};
let seconds = text.strip_suffix('s')?;
if !is_decimal_number(seconds) || seconds.starts_with('-') {
return None;
}
Duration::try_from_secs_f64(seconds.parse().ok()?).ok()
}
pub fn string_match(&self) -> Option<StringMatch<'_>> {
let Value::String(text) = self else {
return None;
};
let leading = text.starts_with('*');
let trailing = text.len() > usize::from(leading) && text.ends_with('*');
let start = usize::from(leading);
let end = text.len() - usize::from(trailing);
let core = &text[start..end.max(start)];
Some(match (leading, trailing) {
(false, false) => StringMatch::Exact(core),
(false, true) => StringMatch::Prefix(core),
(true, false) if core.is_empty() => StringMatch::Contains(core),
(true, false) => StringMatch::Suffix(core),
(true, true) => StringMatch::Contains(core),
})
}
}
fn is_decimal_number(text: &str) -> bool {
let unsigned = text.strip_prefix('-').unwrap_or(text);
let (mantissa, exponent) = match unsigned.find(['e', 'E']) {
Some(index) => (&unsigned[..index], Some(&unsigned[index + 1..])),
None => (unsigned, None),
};
let (integer, fraction) = match mantissa.split_once('.') {
Some((integer, fraction)) => (integer, Some(fraction)),
None => (mantissa, None),
};
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
let exponent_ok = exponent.is_none_or(|e| digits(e.strip_prefix(['+', '-']).unwrap_or(e)));
digits(integer) && fraction.is_none_or(digits) && exponent_ok
}
impl fmt::Display for Comparator {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Comparator::Equal => "=",
Comparator::NotEqual => "!=",
Comparator::GreaterThan => ">",
Comparator::GreaterThanOrEqual => ">=",
Comparator::LessThan => "<",
Comparator::LessThanOrEqual => "<=",
Comparator::Has => ":",
})
}
}
impl fmt::Display for Value {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Value::Text(text) => f.write_str(text),
Value::String(text) => {
f.write_str("\"")?;
for c in text.chars() {
match c {
'"' => f.write_str("\\\"")?,
'\\' => f.write_str("\\\\")?,
'\n' => f.write_str("\\n")?,
'\r' => f.write_str("\\r")?,
'\t' => f.write_str("\\t")?,
c => write!(f, "{c}")?,
}
}
f.write_str("\"")
}
}
}
}
impl fmt::Display for Member {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.value)?;
for field in &self.fields {
write!(f, ".{field}")?;
}
Ok(())
}
}
impl fmt::Display for Function {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}(", self.name.join("."))?;
for (index, arg) in self.args.iter().enumerate() {
if index > 0 {
f.write_str(", ")?;
}
write!(f, "{arg}")?;
}
f.write_str(")")
}
}
impl fmt::Display for Comparable {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Comparable::Member(member) => write!(f, "{member}"),
Comparable::Function(function) => write!(f, "{function}"),
}
}
}
impl fmt::Display for Arg {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Arg::Comparable(comparable) => write!(f, "{comparable}"),
Arg::Composite(expression) => write!(f, "({expression})"),
}
}
}
impl fmt::Display for Restriction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} {} {}", self.comparable, self.comparator, self.arg)
}
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Level {
And,
Sequence,
Or,
Term,
}
impl Expression {
fn level(&self) -> Level {
match self {
Expression::And(_) => Level::And,
Expression::Sequence(_) => Level::Sequence,
Expression::Or(_) => Level::Or,
Expression::Not(_) | Expression::Restriction(_) | Expression::Global(_) => Level::Term,
}
}
fn fmt_child(&self, f: &mut fmt::Formatter<'_>, parent: Level) -> fmt::Result {
if self.level() > parent {
write!(f, "{self}")
} else {
write!(f, "({self})")
}
}
fn fmt_joined(
f: &mut fmt::Formatter<'_>,
children: &[Expression],
separator: &str,
level: Level,
) -> fmt::Result {
for (index, child) in children.iter().enumerate() {
if index > 0 {
f.write_str(separator)?;
}
child.fmt_child(f, level)?;
}
Ok(())
}
}
impl fmt::Display for Expression {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Expression::And(children) => Self::fmt_joined(f, children, " AND ", Level::And),
Expression::Sequence(children) => Self::fmt_joined(f, children, " ", Level::Sequence),
Expression::Or(children) => Self::fmt_joined(f, children, " OR ", Level::Or),
Expression::Not(inner) => match inner.as_ref() {
Expression::Restriction(_) | Expression::Global(_) => write!(f, "NOT {inner}"),
_ => write!(f, "NOT ({inner})"),
},
Expression::Restriction(restriction) => write!(f, "{restriction}"),
Expression::Global(comparable) => write!(f, "{comparable}"),
}
}
}
impl fmt::Display for Filter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.expression {
Some(expression) => write!(f, "{expression}"),
None => Ok(()),
}
}
}