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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
#[derive(Copy, Clone, Debug)]
pub enum Void {}
impl Void {
pub fn absurd(self) -> ! { match self {} }
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Result3<T, E, M> {
Success(T),
FailFast(E),
RetryLater(M),
}
pub trait Maybe {
type Just;
fn just(x: Self::Just) -> Self;
fn is_just(&self) -> bool;
fn is_nothing(&self) -> bool { !self.is_just() }
fn into_optional(self) -> Option<Self::Just>;
}
impl<T> Maybe for Option<T> {
type Just = T;
fn just(x: T) -> Self { Some(x) }
fn is_just(&self) -> bool { self.is_some() }
fn into_optional(self) -> Option<Self::Just> { self }
}
impl<T, E> Maybe for Result<T, E> {
type Just = T;
fn just(x: T) -> Self { Ok(x) }
fn is_just(&self) -> bool { self.is_ok() }
fn into_optional(self) -> Option<T> { self.ok() }
}
impl<T, E, M> Maybe for Result3<T, E, M> {
type Just = T;
fn just(x: T) -> Self { Self::Success(x) }
fn is_just(&self) -> bool { matches!(self, Self::Success(_)) }
fn into_optional(self) -> Option<Self::Just> {
match self {
Self::Success(x) => Some(x),
_ => None,
}
}
}
pub trait Either {
type Left;
type Right;
fn left(x: Self::Left) -> Self;
fn right(x: Self::Right) -> Self;
fn into_result(self) -> Result<Self::Right, Self::Left>;
}
macro_rules! unwrap {
($e: expr) => {
match $crate::utils::Either::into_result($e) {
Ok(x) => x,
Err(e) => return $crate::utils::Either::left(e),
}
}
}
impl<T> Either for Option<T> {
type Left = Option<Void>;
type Right = T;
fn left(_: Option<Void>) -> Self { None }
fn right(x: T) -> Self { Some(x) }
fn into_result(self) -> Result<T, Option<Void>> {
match self {
Some(x) => Ok(x),
None => Err(None),
}
}
}
impl<T, E> Either for Result<T, E> {
type Left = E;
type Right = T;
fn left(x: E) -> Self { Err(x) }
fn right(x: T) -> Self { Ok(x) }
fn into_result(self) -> Result<T, E> { self }
}
impl<T, E> From<T> for Result3<T, E, Void> {
fn from(x: T) -> Self { Self::Success(x) }
}
impl<T, E, M> Either for Result3<T, E, M> {
type Left = M;
type Right = Result3<T, E, Void>;
fn left(m: M) -> Self { Self::RetryLater(m) }
fn right(x: Result3<T, E, Void>) -> Self {
match x {
Result3::Success(x) => Self::Success(x),
Result3::FailFast(e) => Self::FailFast(e),
Result3::RetryLater(m) => m.absurd(),
}
}
fn into_result(self) -> std::result::Result<Result3<T, E, Void>, M> {
match self {
Self::Success(x) => Ok(Result3::Success(x)),
Self::FailFast(e) => Ok(Result3::FailFast(e)),
Self::RetryLater(m) => Err(m),
}
}
}