1#![no_std]
22
23#[cfg(test)]
24extern crate std;
25
26use core::ops::ControlFlow;
27use core::task::Poll;
28
29#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
35pub struct ResultResidual<E>(pub E);
36
37#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
39pub struct OptionResidual;
40
41#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
43pub struct ControlFlowResidual<B>(pub B);
44
45pub trait Try: Sized {
51 type Output;
53
54 type Residual;
56
57 fn branch(self) -> ControlFlow<Self::Residual, Self::Output>;
63}
64
65pub trait FromResidual<Residual = <Self as Try>::Residual> {
67 fn from_residual(residual: Residual) -> Self;
69}
70
71#[inline(always)]
77pub fn branch<T: Try>(val: T) -> ControlFlow<T::Residual, T::Output> {
78 val.branch()
79}
80
81#[inline(always)]
86pub fn from_residual<Target: FromResidual<R>, R>(residual: R) -> Target {
87 Target::from_residual(residual)
88}
89
90impl<T, E> Try for Result<T, E> {
95 type Output = T;
96 type Residual = ResultResidual<E>;
97
98 #[inline(always)]
99 fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
100 match self {
101 Ok(v) => ControlFlow::Continue(v),
102 Err(e) => ControlFlow::Break(ResultResidual(e)),
103 }
104 }
105}
106
107impl<T, E, F: From<E>> FromResidual<ResultResidual<E>> for Result<T, F> {
108 #[inline(always)]
109 fn from_residual(residual: ResultResidual<E>) -> Self {
110 Err(From::from(residual.0))
111 }
112}
113
114impl<T> Try for Option<T> {
119 type Output = T;
120 type Residual = OptionResidual;
121
122 #[inline(always)]
123 fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
124 match self {
125 Some(v) => ControlFlow::Continue(v),
126 None => ControlFlow::Break(OptionResidual),
127 }
128 }
129}
130
131impl<T> FromResidual<OptionResidual> for Option<T> {
132 #[inline(always)]
133 fn from_residual(_residual: OptionResidual) -> Self {
134 None
135 }
136}
137
138impl<B, C> Try for ControlFlow<B, C> {
143 type Output = C;
144 type Residual = ControlFlowResidual<B>;
145
146 #[inline(always)]
147 fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
148 match self {
149 ControlFlow::Continue(c) => ControlFlow::Continue(c),
150 ControlFlow::Break(b) => ControlFlow::Break(ControlFlowResidual(b)),
151 }
152 }
153}
154
155impl<B, C, B2: From<B>> FromResidual<ControlFlowResidual<B>> for ControlFlow<B2, C> {
156 #[inline(always)]
157 fn from_residual(residual: ControlFlowResidual<B>) -> Self {
158 ControlFlow::Break(From::from(residual.0))
159 }
160}
161
162impl<T, E> Try for Poll<Result<T, E>> {
167 type Output = Poll<T>;
168 type Residual = ResultResidual<E>;
169
170 #[inline(always)]
171 fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
172 match self {
173 Poll::Ready(Ok(v)) => ControlFlow::Continue(Poll::Ready(v)),
174 Poll::Ready(Err(e)) => ControlFlow::Break(ResultResidual(e)),
175 Poll::Pending => ControlFlow::Continue(Poll::Pending),
176 }
177 }
178}
179
180impl<T, E, F: From<E>> FromResidual<ResultResidual<E>> for Poll<Result<T, F>> {
181 #[inline(always)]
182 fn from_residual(residual: ResultResidual<E>) -> Self {
183 Poll::Ready(Err(From::from(residual.0)))
184 }
185}
186
187impl<T> Try for Poll<Option<T>> {
188 type Output = Poll<T>;
189 type Residual = OptionResidual;
190
191 #[inline(always)]
192 fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
193 match self {
194 Poll::Ready(Some(v)) => ControlFlow::Continue(Poll::Ready(v)),
195 Poll::Ready(None) => ControlFlow::Break(OptionResidual),
196 Poll::Pending => ControlFlow::Continue(Poll::Pending),
197 }
198 }
199}
200
201impl<T> FromResidual<OptionResidual> for Poll<Option<T>> {
202 #[inline(always)]
203 fn from_residual(_residual: OptionResidual) -> Self {
204 Poll::Ready(None)
205 }
206}
207
208impl<T, E, F: From<E>> FromResidual<ResultResidual<E>> for Option<Result<T, F>> {
210 #[inline(always)]
211 fn from_residual(residual: ResultResidual<E>) -> Self {
212 Some(Err(From::from(residual.0)))
213 }
214}
215
216impl<T, E, F: From<E>> FromResidual<ResultResidual<E>> for Poll<Option<Result<T, F>>> {
218 #[inline(always)]
219 fn from_residual(residual: ResultResidual<E>) -> Self {
220 Poll::Ready(Some(Err(From::from(residual.0))))
221 }
222}
223
224#[macro_export]
230macro_rules! try_op {
231 ($expr:expr) => {
232 match $crate::branch($expr) {
233 ::core::ops::ControlFlow::Continue(val) => val,
234 ::core::ops::ControlFlow::Break(residual) => {
235 return $crate::from_residual(residual);
236 }
237 }
238 };
239}
240
241#[cfg(test)]
246mod tests {
247 use super::*;
248 use core::error::Error;
249 use std::boxed::Box;
250 use std::string::{String, ToString};
251
252 fn parse_int(s: &str) -> Result<i32, core::num::ParseIntError> {
253 s.parse::<i32>()
254 }
255
256 #[test]
257 fn test_result_type_inference_with_error_conversion() {
258 fn run() -> Result<i32, Box<dyn Error>> {
259 let x = try_op!(parse_int("42"));
260 Ok(x * 2)
261 }
262
263 assert_eq!(run().unwrap(), 84);
264
265 fn run_err() -> Result<i32, Box<dyn Error>> {
266 let _ = try_op!(parse_int("not a number"));
267 Ok(0)
268 }
269
270 assert!(run_err().is_err());
271 }
272
273 #[test]
274 fn test_option_desugaring() {
275 fn find_even(v: Option<i32>) -> Option<i32> {
276 let val = try_op!(v);
277 if val % 2 == 0 { Some(val) } else { None }
278 }
279
280 assert_eq!(find_even(Some(4)), Some(4));
281 assert_eq!(find_even(Some(3)), None);
282 assert_eq!(find_even(None), None);
283 }
284
285 #[test]
286 fn test_control_flow_desugaring() {
287 fn search(step: i32) -> ControlFlow<&'static str, i32> {
288 if step > 10 {
289 ControlFlow::Break("limit reached")
290 } else {
291 ControlFlow::Continue(step + 1)
292 }
293 }
294
295 fn run(start: i32) -> ControlFlow<&'static str, i32> {
296 let a = try_op!(search(start));
297 let b = try_op!(search(a));
298 ControlFlow::Continue(b)
299 }
300
301 assert_eq!(run(0), ControlFlow::Continue(2));
302 assert_eq!(run(10), ControlFlow::Break("limit reached"));
303 }
304
305 #[test]
306 fn test_poll_result_desugaring() {
307 fn poll_fn(ready: bool) -> Poll<Result<i32, &'static str>> {
308 if ready {
309 Poll::Ready(Ok(10))
310 } else {
311 Poll::Pending
312 }
313 }
314
315 fn run_poll(ready: bool) -> Poll<Result<i32, String>> {
316 let poll_val = try_op!(poll_fn(ready));
318 match poll_val {
319 Poll::Ready(v) => Poll::Ready(Ok(v * 2)),
320 Poll::Pending => Poll::Pending,
321 }
322 }
323
324 assert_eq!(run_poll(true), Poll::Ready(Ok(20)));
325 assert_eq!(run_poll(false), Poll::Pending);
326 }
327
328 #[test]
329 fn test_result_inside_poll_result_interop() {
330 fn poll_with_sync_check(input: Result<i32, &'static str>) -> Poll<Result<i32, String>> {
332 let val = try_op!(input);
333 Poll::Ready(Ok(val + 1))
334 }
335
336 assert_eq!(poll_with_sync_check(Ok(5)), Poll::Ready(Ok(6)));
337 assert_eq!(
338 poll_with_sync_check(Err("fail")),
339 Poll::Ready(Err("fail".to_string()))
340 );
341 }
342}