Skip to main content

trueno/brick/patterns/
async_result.rs

1//! LCP-12: Async Compute with Sync Fallback
2
3/// Result of an async operation with fallback capability.
4#[derive(Debug, Clone)]
5pub enum AsyncResult<T, E> {
6    /// Operation completed asynchronously
7    Async(T),
8    /// Operation completed synchronously (fallback)
9    Sync(T),
10    /// Operation failed
11    Error(E),
12}
13
14impl<T, E> AsyncResult<T, E> {
15    /// Check if result was obtained asynchronously.
16    #[must_use]
17    pub fn is_async(&self) -> bool {
18        matches!(self, AsyncResult::Async(_))
19    }
20
21    /// Check if result was obtained synchronously (fallback).
22    #[must_use]
23    pub fn is_sync(&self) -> bool {
24        matches!(self, AsyncResult::Sync(_))
25    }
26
27    /// Check if operation failed.
28    #[must_use]
29    pub fn is_error(&self) -> bool {
30        matches!(self, AsyncResult::Error(_))
31    }
32
33    /// Get the result value, regardless of async/sync.
34    pub fn into_result(self) -> Result<T, E> {
35        match self {
36            AsyncResult::Async(v) | AsyncResult::Sync(v) => Ok(v),
37            AsyncResult::Error(e) => Err(e),
38        }
39    }
40
41    /// Map the success value.
42    pub fn map<U>(self, f: impl FnOnce(T) -> U) -> AsyncResult<U, E> {
43        match self {
44            AsyncResult::Async(v) => AsyncResult::Async(f(v)),
45            AsyncResult::Sync(v) => AsyncResult::Sync(f(v)),
46            AsyncResult::Error(e) => AsyncResult::Error(e),
47        }
48    }
49}