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
use codegen::CallSite;
use extract::{Context, Error, Extract, ExtractFuture};
use util::buf_stream::{self, BufStream};

use futures::{Future, Poll};

/// Extract a value using `serde`
#[derive(Debug)]
pub struct ExtractBytes<T, B> {
    state: State<T, B>,
}

#[derive(Debug)]
enum State<T, B> {
    Complete(Result<T, Option<Error>>),
    Body(buf_stream::Collect<B, Vec<u8>>),
}

impl<B: BufStream> Extract<B> for Vec<u8> {
    type Future = ExtractBytes<Self, B>;

    fn extract(ctx: &Context) -> Self::Future {
        use codegen::Source::*;

        match ctx.callsite().source() {
            Capture(idx) => {
                let path = ctx.request().uri().path();
                let value = ctx.captures().get(*idx, path)
                    .into();

                let state = State::Complete(Ok(value));
                ExtractBytes { state }
            }
            Header(header_name) => {
                let value = match ctx.request().headers().get(header_name) {
                    Some(value) => value,
                    None => {
                        return ExtractBytes::err(Error::missing_argument());
                    }
                };

                ExtractBytes::ok(value.as_bytes().into())
            }
            QueryString => {
                let query = ctx.request().uri()
                    .path_and_query()
                    .and_then(|path_and_query| path_and_query.query())
                    .unwrap_or("");

                ExtractBytes::ok(query.into())
            }
            Body => {
                panic!("called `extract` but `body` is required");
            }
            Unknown => {
                unimplemented!();
            }
        }
    }

    fn extract_body(ctx: &Context, body: B) -> Self::Future {
        use codegen::Source::*;

        match ctx.callsite().source() {
            Body => {
                let state = State::Body(body.collect());
                ExtractBytes { state }
            }
            _ => panic!("called `extract_body` but not extracting from body"),
        }
    }

    fn requires_body(callsite: &CallSite) -> bool {
        callsite.requires_body()
    }
}

impl<T, B> ExtractBytes<T, B> {
    /// Create an `ExtractBytes` in the completed state
    fn ok(value: T) -> Self {
        let state = State::Complete(Ok(value));
        ExtractBytes { state }
    }

    /// Create an `ExtractBytes` in the error state
    fn err(err: Error) -> Self {
        let state = State::Complete(Err(Some(err)));
        ExtractBytes { state }
    }
}

impl<T, B> ExtractFuture for ExtractBytes<T, B>
where T: From<Vec<u8>>,
      B: BufStream,
{
    type Item = T;

    fn poll(&mut self) -> Poll<(), Error> {
        use self::State::*;

        loop {
            let res = match self.state {
                Complete(Err(ref mut e)) => {
                    return Err(e.take().unwrap());
                }
                Complete(Ok(_)) => {
                    return Ok(().into());
                }
                Body(ref mut collect) => {
                    let res = collect.poll()
                        // TODO: Is there a better way to handle errors?
                        .map_err(|_| Error::internal_error());

                    try_ready!(res).into()
                }
            };

            self.state = State::Complete(Ok(res));
        }
    }

    fn extract(self) -> T {
        use self::State::Complete;

        match self.state {
            Complete(Ok(res)) => res,
            _ => panic!("invalid state"),
        }
    }
}