Skip to content

Commit

Permalink
ffi: wrap external functions in Arc, which is thread-safe
Browse files Browse the repository at this point in the history
`RunLimits` are typically sent between threads eg when starting an HTTP server, so they need to be `Send`
  • Loading branch information
divarvel committed Oct 23, 2024
1 parent e11e630 commit 8093cfe
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions biscuit-auth/src/datalog/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ use super::{SymbolTable, TemporarySymbolTable};
use regex::Regex;
use std::collections::{HashMap, HashSet};
use std::convert::TryFrom;
use std::rc::Rc;
use std::sync::Arc;

#[derive(Clone)]
pub struct ExternFunc(
pub Rc<dyn Fn(builder::Term, Option<builder::Term>) -> Result<builder::Term, String>>,
pub Arc<
dyn Fn(builder::Term, Option<builder::Term>) -> Result<builder::Term, String> + Send + Sync,
>,
);

impl std::fmt::Debug for ExternFunc {
Expand All @@ -20,7 +22,11 @@ impl std::fmt::Debug for ExternFunc {

impl ExternFunc {
pub fn new(
f: Rc<dyn Fn(builder::Term, Option<builder::Term>) -> Result<builder::Term, String>>,
f: Arc<
dyn Fn(builder::Term, Option<builder::Term>) -> Result<builder::Term, String>
+ Send
+ Sync,
>,
) -> Self {
Self(f)
}
Expand Down Expand Up @@ -1689,7 +1695,7 @@ mod tests {
let mut extern_funcs: HashMap<String, ExternFunc> = Default::default();
extern_funcs.insert(
"test_bin".to_owned(),
ExternFunc::new(Rc::new(|left, right| match (left, right) {
ExternFunc::new(Arc::new(|left, right| match (left, right) {
(builder::Term::Integer(left), Some(builder::Term::Integer(right))) => {
println!("{left} {right}");
Ok(builder::Term::Bool((left % 60) == (right % 60)))
Expand All @@ -1705,7 +1711,7 @@ mod tests {
);
extern_funcs.insert(
"test_un".to_owned(),
ExternFunc::new(Rc::new(|left, right| match (&left, &right) {
ExternFunc::new(Arc::new(|left, right| match (&left, &right) {
(builder::Term::Integer(left), None) => Ok(builder::boolean(*left == 42)),
_ => {
println!("{left:?}, {right:?}");
Expand Down

0 comments on commit 8093cfe

Please sign in to comment.