pub type Function = dyn for<'a> Fn(&Value<'a>) -> Value<'a> + Send + Sync;Expand description
Alias for a trait object that represents a function that can be called from Dent. The function takes a reference to a value and returns a value.
The function can be called from Dent using the @ operator, after
being registered with Dent::add_function.
A Dent function can only take a single argument, for simplicity. If you need to pass multiple arguments, you can use a list or dictionary.
ยงExamples
use dent_parse::{Dent, Value, Function};
use std::collections::HashMap;
let mut functions: HashMap<String, Box<Function>> = HashMap::new();
functions.insert(
"sum".to_string(),
Box::new(move |value: &Value| -> Value {
let mut sum = 0;
if let Value::List(values) = value {
for value in values.iter() {
if let Value::Int(i) = value {
sum += i;
}
}
Value::Int(sum)
} else if let Value::Int(i) = value {
Value::Int(*i)
} else {
Value::None
}
}),
);
let parser = Dent::new(functions);
assert_eq!(parser.parse("@sum {}"), Ok(Value::None));
assert_eq!(parser.parse("@sum 0"), Ok(Value::Int(0)));
assert_eq!(parser.parse("@sum [ 1 2 3 ]"), Ok(Value::Int(6)));