Skip to main content

Function

Trait Function 

Source
pub trait Function: Send + Sync {
    // Required methods
    fn name(&self) -> &str;
    fn arity(&self) -> usize;
    fn call<'a>(
        &self,
        args: &[Cow<'a, FilterValue<'a>>],
    ) -> Cow<'a, FilterValue<'a>>;
}
Expand description

A function which can be called from within a filter expression using the familiar name(args...) syntax.

The crate provides a small set of built-in functions, but you can define your own by implementing this trait and registering instances with Filter::with_functions. A function reports its name and arity so the parser can resolve and validate calls up-front, and evaluates via call.

Implementations must be Send + Sync so that a parsed Filter can be shared across threads.

use std::borrow::Cow;
use filt_rs::{FilterValue, Function};

/// A `len(string)` function returning the number of characters in its argument.
struct Len;

impl Function for Len {
    fn name(&self) -> &str {
        "len"
    }

    fn arity(&self) -> usize {
        1
    }

    fn call<'a>(&self, args: &[Cow<'a, FilterValue<'a>>]) -> Cow<'a, FilterValue<'a>> {
        match args[0].as_ref() {
            FilterValue::String(s) => Cow::Owned(FilterValue::Number(s.chars().count() as f64)),
            _ => Cow::Owned(FilterValue::Null),
        }
    }
}

assert_eq!(Len.name(), "len");
assert_eq!(Len.arity(), 1);

Required Methods§

Source

fn name(&self) -> &str

The name used to invoke this function in a filter expression.

Source

fn arity(&self) -> usize

The exact number of arguments this function accepts.

The parser checks a call’s argument count against this when the filter is parsed, so a mismatch fails fast with a friendly error rather than at evaluation time.

Source

fn call<'a>( &self, args: &[Cow<'a, FilterValue<'a>>], ) -> Cow<'a, FilterValue<'a>>

Evaluates the function against its already-evaluated arguments.

The slice is guaranteed to hold exactly arity elements (the parser enforces this), so implementations may index into it directly. Returning a value which borrows from the arguments — for example a trimmed sub-slice of a borrowed string — keeps evaluation allocation-free, mirroring the rest of the interpreter.

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§