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
// Copyright © 2021 Alexandra Frydl
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

use super::*;

/// A [`Future`] that returns a result.
pub trait TryFuture<T, E>: Future<Output = Result<T, E>> {}

impl<F, T, E> TryFuture<T, E> for F where F: Future<Output = Result<T, E>> {}

/// Extension methods for futures that return a result.
pub trait TryFutureExt<T, E>: Sized {
  /// Returns a new future that converts the error by applying a function.
  fn map_err<F, M>(self, map: M) -> MapErr<Self, M>
  where
    M: FnOnce(E) -> F,
  {
    MapErr { future: self, map: Some(map) }
  }
}

impl<F, T, E> TryFutureExt<T, E> for F where F: TryFuture<T, E> {}

/// A [`TryFuture`] that modifies the original error.
#[pin_project]
pub struct MapErr<F, M> {
  #[pin]
  future: F,
  map: Option<M>,
}

impl<T, I, O, F, M> Future for MapErr<F, M>
where
  F: Future<Output = Result<T, I>>,
  M: FnOnce(I) -> O,
{
  type Output = Result<T, O>;

  fn poll(self: Pin<&mut Self>, cx: &mut future::Context<'_>) -> future::Poll<Self::Output> {
    let this = self.project();

    match this.future.poll(cx) {
      future::Poll::Ready(res) => future::Poll::Ready(res.map_err(this.map.take().unwrap())),
      future::Poll::Pending => future::Poll::Pending,
    }
  }
}