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
//! Types used to extract `Option` values from an HTTP request.

use extract::{Extract, ExtractFuture, Error, Context};
use util::BufStream;

use futures::{Async, Poll};

/// Extract an `Option` value from an HTTP request.
#[derive(Debug)]
pub struct ExtractOptionFuture<T> {
    inner: T,
    none: bool,
}

impl<T, B: BufStream> Extract<B> for Option<T>
where T: Extract<B>,
{
    type Future = ExtractOptionFuture<T::Future>;

    fn extract(ctx: &Context) -> Self::Future {
        ExtractOptionFuture {
            inner: T::extract(ctx),
            none: false,
        }
    }
}

impl<T> ExtractFuture for ExtractOptionFuture<T>
where T: ExtractFuture,
{
    type Item = Option<T::Item>;

    fn poll(&mut self) -> Poll<(), Error> {
        match self.inner.poll() {
            Err(ref e) if e.is_missing_argument() => {
                self.none = true;
                Ok(Async::Ready(()))
            }
            res => res,
        }
    }

    fn extract(self) -> Self::Item {
        if self.none {
            None
        } else {
            Some(self.inner.extract())
        }
    }
}