easerx/
execution_result.rs

1use crate::Async;
2
3/// A trait for converting various result types into the `Async<T>` representation.
4///
5/// This trait provides a unified way to convert different result types (direct values, 
6/// `Result<T, E>`, and `Option<T>`) into the `Async<T>` type used throughout the EaseRx framework.
7/// It simplifies error handling by automatically converting various error types into
8/// the appropriate `Async` variant.
9///
10/// Implementors of this trait can be used directly with the execution methods of `StateStore`.
11pub trait ExecutionResult<T: Clone> {
12    /// Converts the implementor into an `Async<T>` representation.
13    ///
14    /// This method handles the conversion logic for each specific result type,
15    /// ensuring appropriate error handling and state representation.
16    fn into_async(self) -> Async<T>;
17}
18
19/// Implementation for direct values of type `T`.
20///
21/// This implementation wraps the value in `Async::Success`.
22impl<T: Clone> ExecutionResult<T> for T {
23    fn into_async(self) -> Async<T> {
24        Async::success(self)
25    }
26}
27
28/// Implementation for `Result<T, E>` where `E` can be converted to a string.
29///
30/// This implementation converts:
31/// - `Ok(value)` to `Async::Success { value }`
32/// - `Err(error)` to `Async::Fail` with the error message
33impl<T: Clone, E> ExecutionResult<T> for Result<T, E>
34where
35    E: ToString,
36{
37    fn into_async(self) -> Async<T> {
38        match self {
39            Ok(value) => Async::success(value),
40            Err(error) => Async::fail_with_message(error.to_string(), None),
41        }
42    }
43}
44
45/// Implementation for `Option<T>`.
46///
47/// This implementation converts:
48/// - `Some(value)` to `Async::Success { value }`
49/// - `None` to `Async::Fail` with a None error
50impl<T: Clone> ExecutionResult<T> for Option<T> {
51    fn into_async(self) -> Async<T> {
52        match self {
53            Some(value) => Async::success(value),
54            None => Async::fail_with_none(None),
55        }
56    }
57}