spin_templates/
cancellable.rs1pub(crate) enum Cancellable<T, E> {
2 Cancelled,
3 Err(E),
4 Ok(T),
5}
6
7impl<T, E> Cancellable<T, E> {
8 pub(crate) fn err(self) -> Result<(), E> {
9 match self {
10 Self::Ok(_) => Ok(()),
11 Self::Cancelled => Ok(()),
12 Self::Err(e) => Err(e),
13 }
14 }
15
16 pub(crate) fn and_then<U>(self, f: impl Fn(T) -> Result<U, E>) -> Cancellable<U, E> {
17 match self {
18 Self::Ok(value) => match f(value) {
19 Ok(r) => Cancellable::Ok(r),
20 Err(e) => Cancellable::Err(e),
21 },
22 Self::Cancelled => Cancellable::Cancelled,
23 Self::Err(e) => Cancellable::Err(e),
24 }
25 }
26
27 pub(crate) async fn and_then_async<U, Fut: std::future::Future<Output = Result<U, E>>>(
28 self,
29 f: impl Fn(T) -> Fut,
30 ) -> Cancellable<U, E> {
31 match self {
32 Self::Ok(value) => match f(value).await {
33 Ok(r) => Cancellable::Ok(r),
34 Err(e) => Cancellable::Err(e),
35 },
36 Self::Cancelled => Cancellable::Cancelled,
37 Self::Err(e) => Cancellable::Err(e),
38 }
39 }
40}
41
42impl<T, E> From<Result<Option<T>, E>> for Cancellable<T, E> {
43 fn from(ro: Result<Option<T>, E>) -> Self {
44 match ro {
45 Ok(Some(t)) => Self::Ok(t),
46 Ok(None) => Self::Cancelled,
47 Err(e) => Self::Err(e),
48 }
49 }
50}