pub struct Filter { /* private fields */ }Expand description
A parsed filter expression which can be evaluated against Filterable objects.
A Filter is constructed from a textual filter expression using
Filter::new, which tokenizes and parses the expression up-front so that
it can be cheaply evaluated against any number of objects using
Filter::matches.
use filt_rs::{Filter, FilterValue, Filterable};
struct Server {
hostname: &'static str,
port: u16,
}
impl Filterable for Server {
fn get(&self, key: &str) -> FilterValue<'_> {
match key {
"hostname" => self.hostname.into(),
"port" => self.port.into(),
_ => FilterValue::Null,
}
}
}
let filter = Filter::new(r#"hostname startswith "web" && port == 443"#)?;
assert!(filter.matches(&Server { hostname: "web-01", port: 443 })?);
assert!(!filter.matches(&Server { hostname: "db-01", port: 5432 })?);The default filter is the expression true, which matches every object:
let filter = Filter::default();
assert_eq!(filter.raw(), "true");
assert!(filter.matches(&Anything).unwrap());Implementations§
Source§impl Filter
impl Filter
Sourcepub fn new<S: Into<String>>(filter: S) -> Result<Self, Error>
pub fn new<S: Into<String>>(filter: S) -> Result<Self, Error>
Parses the provided filter expression, returning a reusable Filter.
The expression is tokenized and parsed eagerly, so any syntax errors are reported here rather than at evaluation time. Errors include the location of the problem and guidance on how to correct it.
use filt_rs::Filter;
let filter = Filter::new("size > 100 && !archived").unwrap();
assert_eq!(filter.raw(), "size > 100 && !archived");
let error = Filter::new("size >").unwrap_err();
assert!(error.to_string().contains("end of your filter expression"));Sourcepub fn matches<T: Filterable>(&self, target: &T) -> Result<bool, Error>
pub fn matches<T: Filterable>(&self, target: &T) -> Result<bool, Error>
Evaluates this filter against the provided object, returning whether it matched.
The object’s properties are resolved through its Filterable::get
implementation, and the filter matches when the expression evaluates to
a truthy value.
use filt_rs::{Filter, FilterValue, Filterable};
struct Message(&'static str);
impl Filterable for Message {
fn get(&self, key: &str) -> FilterValue<'_> {
match key {
"subject" => self.0.into(),
_ => FilterValue::Null,
}
}
}
let filter = Filter::new(r#"subject contains "invoice""#)?;
assert!(filter.matches(&Message("Invoice #123"))?);
assert!(!filter.matches(&Message("Weekly newsletter"))?);Trait Implementations§
Source§impl Debug for Filter
impl Debug for Filter
Source§fn fmt(&self, f: &mut Formatter<'_>) -> Result
fn fmt(&self, f: &mut Formatter<'_>) -> Result
Formats the filter as its parsed expression tree, which can be useful when debugging operator precedence issues.
use filt_rs::Filter;
let filter = Filter::new("a || b && c").unwrap();
assert_eq!(format!("{filter:?}"), "(|| (property a) (&& (property b) (property c)))");