Skip to content

Commit

Permalink
🔨 Add Rule type + module to durin_primitives
Browse files Browse the repository at this point in the history
  • Loading branch information
clabby committed Sep 9, 2023
1 parent fa3d332 commit 4efe19b
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 0 deletions.
3 changes: 3 additions & 0 deletions crates/primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,6 @@ pub use dispute_game::{Claim, GameStatus, GameType};

mod traits;
pub use traits::{DisputeGame, DisputeSolver};

#[cfg(test)]
pub mod rule;
84 changes: 84 additions & 0 deletions crates/primitives/src/rule.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
//! This module contains the [Rule] type as well as several helper macros for applying
//! rules on top of one another.
type Rule<T> = Box<dyn Fn(T) -> anyhow::Result<T>>;

#[macro_export]
macro_rules! chain_rules {
($state:expr, $($rule:expr),+) => {{
let mut result = Ok($state);

$(
result = match result {
Ok(val) => $rule(val),
err @ Err(_) => err,
};
)+

result
}};
}

mod test {
use super::*;

#[test]
fn apply_sequential_rules() {
let state = 5;

let rule_lt_10: Rule<u32> = Box::new(|state: u32| {
if state < 10 {
Ok(state)
} else {
Err(anyhow::anyhow!("state must be less than 10"))
}
});
let rule_double_10: Rule<u32> = Box::new(|state: u32| {
if state * 2 == 10 {
Ok(state)
} else {
Err(anyhow::anyhow!("state must be half of 10"))
}
});
let rule_bitwise: Rule<u32> = Box::new(|state: u32| {
if state & 0xF == 0b0101 {
Ok(state)
} else {
Err(anyhow::anyhow!("state must be 5"))
}
});

let result = chain_rules!(state, rule_lt_10, rule_double_10, rule_bitwise);
assert!(result.is_ok());
}

#[test]
fn fail_sequential_rules() {
let state = 5;

let rule_lt_10: Rule<u32> = Box::new(|state: u32| {
if state < 10 {
Ok(state)
} else {
Err(anyhow::anyhow!("state must be less than 10"))
}
});
let rule_double_11: Rule<u32> = Box::new(|state: u32| {
if state * 2 == 11 {
Ok(state)
} else {
Err(anyhow::anyhow!("state must be half of 11"))
}
});
let rule_bitwise: Rule<u32> = Box::new(|state: u32| {
if state & 0xF == 0b0101 {
Ok(state)
} else {
Err(anyhow::anyhow!("state must be 5"))
}
});

let result = chain_rules!(state, rule_lt_10, rule_double_11, rule_bitwise);
assert!(result.is_err());
}
}

0 comments on commit 4efe19b

Please sign in to comment.