retry_predicate/predicates/
fn.rs

1use alloc::boxed::Box;
2use core::fmt;
3
4use crate::retry_predicate::RetryPredicate;
5
6//
7pub struct Predicate<Params> {
8    f: Box<dyn Fn(&Params) -> bool + Send + Sync>,
9}
10
11impl<Params> fmt::Debug for Predicate<Params> {
12    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
13        f.debug_struct("FnPredicate").finish_non_exhaustive()
14    }
15}
16
17impl<F, Params> From<F> for Predicate<Params>
18where
19    F: Fn(&Params) -> bool + Send + Sync + 'static,
20{
21    fn from(f: F) -> Self {
22        Self { f: Box::new(f) }
23    }
24}
25
26//
27impl<Params> RetryPredicate<Params> for Predicate<Params> {
28    fn test(&self, params: &Params) -> bool {
29        (self.f)(params)
30    }
31
32    fn name(&self) -> &str {
33        "Fn"
34    }
35}
36
37//
38#[cfg(test)]
39fn fn_demo(_params: &usize) -> bool {
40    true
41}
42
43#[cfg(test)]
44mod tests {
45    use super::*;
46
47    #[test]
48    fn test_from_f() {
49        let _ = Predicate::from(fn_demo);
50        let _ = Predicate::from(|_params: &usize| true);
51    }
52
53    #[test]
54    fn test_impl_retry_predicate() {
55        let predicate = Predicate::from(fn_demo);
56
57        assert!(Predicate::test(&predicate, &0));
58        assert_eq!(Predicate::name(&predicate), "Fn");
59    }
60}