Skip to main content

imagineer/
combinators.rs

1pub trait FallbackIf<T, E> {
2    fn fallback_if<P, F, V>(self, predicate: P, f: F, alternative: V) -> Result<T, E>
3    where
4        P: Into<bool>,
5        F: FnOnce(V) -> Result<T, E>;
6}
7
8impl<T, E> FallbackIf<T, E> for Result<T, E> {
9    /// Fallback to an alternative when a result produces an error and the predicate evaluates to true,
10    /// otherwise keep the current result
11    fn fallback_if<P, F, V>(self, predicate: P, f: F, alternative: V) -> Result<T, E>
12    where
13        P: Into<bool>,
14        F: FnOnce(V) -> Result<T, E>,
15    {
16        if self.is_err() && predicate.into() {
17            f(alternative)
18        } else {
19            self
20        }
21    }
22}