When implementing custom functions, use Rhai's Dynamic methods to extract the required types from arguments:
- Strings: Use
dynamic_to_str(&dynamic) from casbin::model::function_map or .to_string(). - Integers: Use
.as_int().unwrap_or(default_value). - Booleans: Use
.as_bool().unwrap_or(default_value). - Floats: Use
.as_float().unwrap_or(default_value).
Examples
String-based (using dynamic_to_str)
use casbin::model::function_map::dynamic_to_str;
e.add_function(
"stringContains",
OperatorFunction::Arg2(|haystack: Dynamic, needle: Dynamic| {
let haystack_str = dynamic_to_str(&haystack);
let needle_str = dynamic_to_str(&needle);
haystack_str.contains(needle_str.as_ref()).into()
}),
);
Integer-based
e.add_function(
"greaterThan",
OperatorFunction::Arg2(|a: Dynamic, b: Dynamic| {
let a_int = a.as_int().unwrap_or(0);
let b_int = b.as_int().unwrap_or(0);
(a_int > b_int).into()
}),
);
Multi-argument and Mixed-type
e.add_function(
"complexCheck",
OperatorFunction::Arg3(|name: Dynamic, age: Dynamic, is_admin: Dynamic| {
let name_str = name.to_string();
let age_int = age.as_int().unwrap_or(0);
let admin_bool = is_admin.as_bool().unwrap_or(false);
let result = name_str.len() > 3 && age_int >= 18 && admin_bool;
result.into()
}),
);