1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//! Fallback combinator for providing default values on error.
use crate::effect::Effect;
/// Provides a default value on any error.
///
/// Zero-cost: no heap allocation. Stores only the inner effect
/// and the default value.
///
/// # Examples
///
/// ```rust,ignore
/// use stillwater::effect::prelude::*;
///
/// let count = get_count().fallback(0);
/// // Returns 0 on any error
/// ```
pub struct Fallback<E>
where
E: Effect,
{
pub(crate) inner: E,
pub(crate) default: E::Output,
}
impl<E> std::fmt::Debug for Fallback<E>
where
E: Effect,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Fallback")
.field("inner", &"<effect>")
.field("default", &"<value>")
.finish()
}
}
impl<E> Fallback<E>
where
E: Effect,
{
/// Creates a new `Fallback` combinator.
///
/// # Parameters
/// - `inner`: The effect to execute
/// - `default`: The default value to return if the effect fails
pub fn new(inner: E, default: E::Output) -> Self {
Self { inner, default }
}
}
impl<E> Effect for Fallback<E>
where
E: Effect,
E::Output: Send,
{
type Output = E::Output;
type Error = E::Error;
type Env = E::Env;
async fn run(self, env: &Self::Env) -> Result<Self::Output, Self::Error> {
match self.inner.run(env).await {
Ok(value) => Ok(value),
Err(_) => Ok(self.default),
}
}
}