tower_web/extract/
immediate.rs

1use extract::{ExtractFuture, Error};
2
3use futures::{Poll};
4
5/// Implements `ExtractFuture` such that the result is immediately available.
6///
7/// This type is useful when implementing `Extract` for types that do not
8/// require any asynchronous processing. For example, extracting an HTTP header
9/// value from an HTTP request can complete immediately as all the information
10/// is present.
11#[derive(Debug)]
12pub struct Immediate<T> {
13    inner: Result<T, Option<Error>>,
14}
15
16impl<T> Immediate<T> {
17    /// Create a new `Immediate` instance from a `Result` value.
18    ///
19    /// When polling the returned `Immediate` instance, it will yield `result`.
20    pub fn result(result: Result<T, Error>) -> Immediate<T> {
21        Immediate {
22            inner: result.map_err(Some),
23        }
24    }
25
26    /// Create a new `Immediate` instance that is in the success state.
27    ///
28    /// When polling the returned `Immediate` instance, it will yield `value`.
29    pub fn ok(value: T) -> Immediate<T> {
30        Immediate::result(Ok(value))
31    }
32
33    /// Create a new `Immediate` instance that is in the error state.
34    ///
35    /// When polling the returned `Immediate` instance, it will yield `error`.
36    pub fn err(error: Error) -> Immediate<T> {
37        Immediate::result(Err(error))
38    }
39}
40
41impl<T> ExtractFuture for Immediate<T> {
42    type Item = T;
43
44    fn poll(&mut self) -> Poll<(), Error> {
45        match self.inner {
46            Ok(_) => Ok(().into()),
47            Err(ref mut err) => {
48                Err(err.take().unwrap())
49            }
50        }
51    }
52
53    fn extract(self) -> T {
54        self.inner.unwrap()
55    }
56}
57
58impl<T, E> From<Result<T, E>> for Immediate<T>
59where E: Into<Error>,
60{
61    fn from(src: Result<T, E>) -> Self {
62        let inner = src.map_err(|e| Some(e.into()));
63        Immediate { inner }
64    }
65}