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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
use bytecodec::tuple::TupleDecoder;
use bytecodec::{ByteCount, Decode, Encode, Eos, Result, SizedEncode};
use std::fmt;
use std::str;

use header::HeaderFieldPosition;
use message::{Message, MessageDecoder, MessageEncoder};
use status::{ReasonPhraseDecoder, StatusCodeDecoder};
use util::SpaceDecoder;
use version::HttpVersionDecoder;
use {
    BodyDecode, BodyEncode, DecodeOptions, Header, HeaderMut, HttpVersion, ReasonPhrase, StatusCode,
};

/// HTTP response message.
#[derive(Debug)]
pub struct Response<T> {
    buf: Vec<u8>,
    status_line: StatusLine,
    header: Vec<HeaderFieldPosition>,
    body: T,
}
impl<T> Response<T> {
    /// Makes a new `Response` instance with the given status-line components and body.
    pub fn new(version: HttpVersion, status: StatusCode, reason: ReasonPhrase, body: T) -> Self {
        let mut buf = Vec::new();
        buf.extend_from_slice(version.as_str().as_bytes());
        buf.push(b' ');
        buf.extend_from_slice(&status.as_bytes()[..]);
        buf.push(b' ');
        buf.extend_from_slice(reason.as_str().as_bytes());
        buf.extend_from_slice(b"\r\n");

        let status_line = StatusLine {
            http_version: version,
            status_code: status,
            reason_phrase_size: reason.as_str().len(),
        };

        Response {
            buf,
            status_line,
            header: Vec::new(),
            body,
        }
    }

    /// Returns the HTTP version of the response.
    pub fn http_version(&self) -> HttpVersion {
        self.status_line.http_version
    }

    /// Returns the status code of the response.
    pub fn status_code(&self) -> StatusCode {
        self.status_line.status_code
    }

    /// Returns the reason phrase of the response.
    pub fn reason_phrase(&self) -> ReasonPhrase {
        let start = 8 /* version */ + 1 + 3 /* status */ + 1;
        let end = start + self.status_line.reason_phrase_size;
        unsafe { ReasonPhrase::new_unchecked(str::from_utf8_unchecked(&self.buf[start..end])) }
    }

    /// Returns the header of the response.
    pub fn header(&self) -> Header {
        Header::new(&self.buf, &self.header)
    }

    /// Returns the mutable header of the response.
    pub fn header_mut(&mut self) -> HeaderMut {
        HeaderMut::new(&mut self.buf, &mut self.header)
    }

    /// Returns a reference to the body of the response.
    pub fn body(&self) -> &T {
        &self.body
    }

    /// Returns a mutable reference to the body of the response.
    pub fn body_mut(&mut self) -> &mut T {
        &mut self.body
    }

    /// Converts the body of the response to `U` by using the given function.
    pub fn map_body<U, F>(self, f: F) -> Response<U>
    where
        F: FnOnce(T) -> U,
    {
        let body = f(self.body);
        Response {
            buf: self.buf,
            status_line: self.status_line,
            header: self.header,
            body,
        }
    }

    /// Takes ownership of the response, and returns its body.
    pub fn into_body(self) -> T {
        self.body
    }

    /// Splits the head part and the body part of the response.
    pub fn take_body(self) -> (Response<()>, T) {
        let res = Response {
            buf: self.buf,
            status_line: self.status_line,
            header: self.header,
            body: (),
        };
        (res, self.body)
    }
}
impl<T: fmt::Display> fmt::Display for Response<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(
            f,
            "{} {} {}\r",
            self.http_version(),
            self.status_code(),
            self.reason_phrase(),
        )?;
        write!(f, "{}", self.header())?;
        write!(f, "{}", self.body)?;
        Ok(())
    }
}

#[derive(Debug)]
struct StatusLine {
    http_version: HttpVersion,
    status_code: StatusCode,
    reason_phrase_size: usize,
}

#[derive(Debug, Default)]
struct StatusLineDecoder(
    TupleDecoder<(
        HttpVersionDecoder,
        SpaceDecoder,
        StatusCodeDecoder,
        ReasonPhraseDecoder,
    )>,
);
impl Decode for StatusLineDecoder {
    type Item = StatusLine;

    fn decode(&mut self, buf: &[u8], eos: Eos) -> Result<usize> {
        track!(self.0.decode(buf, eos))
    }

    fn finish_decoding(&mut self) -> Result<Self::Item> {
        let t = track!(self.0.finish_decoding())?;
        Ok(StatusLine {
            http_version: t.0,
            status_code: t.2,
            reason_phrase_size: t.3,
        })
    }

    fn requiring_bytes(&self) -> ByteCount {
        self.0.requiring_bytes()
    }

    fn is_idle(&self) -> bool {
        self.0.is_idle()
    }
}

/// HTTP response decoder.
#[derive(Debug)]
pub struct ResponseDecoder<D>(MessageDecoder<StatusLineDecoder, D>);
impl<D: BodyDecode> ResponseDecoder<D> {
    /// Make a new `ResponseDecoder` instance.
    pub fn new(body_decoder: D) -> Self {
        Self::with_options(body_decoder, DecodeOptions::default())
    }

    /// Make a new `ResponseDecoder` instance with the given options.
    pub fn with_options(body_decoder: D, options: DecodeOptions) -> Self {
        let inner = MessageDecoder::new(StatusLineDecoder::default(), body_decoder, options);
        ResponseDecoder(inner)
    }
}
impl<D: BodyDecode> Decode for ResponseDecoder<D> {
    type Item = Response<D::Item>;

    fn decode(&mut self, buf: &[u8], eos: Eos) -> Result<usize> {
        track!(self.0.decode(buf, eos))
    }

    fn finish_decoding(&mut self) -> Result<Self::Item> {
        let m = track!(self.0.finish_decoding())?;
        Ok(Response {
            buf: m.buf,
            status_line: m.start_line,
            header: m.header,
            body: m.body,
        })
    }

    fn requiring_bytes(&self) -> ByteCount {
        self.0.requiring_bytes()
    }

    fn is_idle(&self) -> bool {
        self.0.is_idle()
    }
}
impl<D: Default + BodyDecode> Default for ResponseDecoder<D> {
    fn default() -> Self {
        Self::new(D::default())
    }
}

/// HTTP response encoder.
#[derive(Debug, Default)]
pub struct ResponseEncoder<E>(MessageEncoder<E>);
impl<E: BodyEncode> ResponseEncoder<E> {
    /// Makes a new `ResponseEncoder` instance.
    pub fn new(body_encoder: E) -> Self {
        ResponseEncoder(MessageEncoder::new(body_encoder))
    }
}
impl<E: BodyEncode> Encode for ResponseEncoder<E> {
    type Item = Response<E::Item>;

    fn encode(&mut self, buf: &mut [u8], eos: Eos) -> Result<usize> {
        track!(self.0.encode(buf, eos))
    }

    fn start_encoding(&mut self, item: Self::Item) -> Result<()> {
        let item = Message {
            buf: item.buf,
            start_line: (),
            header: item.header,
            body: item.body,
        };
        track!(self.0.start_encoding(item))
    }

    fn is_idle(&self) -> bool {
        self.0.is_idle()
    }

    fn requiring_bytes(&self) -> ByteCount {
        self.0.requiring_bytes()
    }
}
impl<E: SizedEncode + BodyEncode> SizedEncode for ResponseEncoder<E> {
    fn exact_requiring_bytes(&self) -> u64 {
        self.0.exact_requiring_bytes()
    }
}

#[cfg(test)]
mod test {
    use bytecodec::bytes::{BytesEncoder, RemainingBytesDecoder, Utf8Decoder};
    use bytecodec::io::{IoDecodeExt, IoEncodeExt};
    use bytecodec::EncodeExt;

    use super::*;
    use {BodyDecoder, BodyEncoder, HttpVersion, ReasonPhrase, StatusCode};

    #[test]
    fn response_encoder_works() {
        let response = Response::new(
            HttpVersion::V1_0,
            StatusCode::new(200).unwrap(),
            ReasonPhrase::new("OK").unwrap(),
            b"barbaz",
        );
        let mut encoder =
            ResponseEncoder::<BodyEncoder<BytesEncoder<_>>>::with_item(response).unwrap();

        let mut buf = Vec::new();
        track_try_unwrap!(encoder.encode_all(&mut buf));
        assert_eq!(
            buf,
            b"HTTP/1.0 200 OK\r\nContent-Length: 6\r\n\r\nbarbaz".as_ref()
        );
    }

    #[test]
    fn response_decoder_works() {
        let mut decoder =
            ResponseDecoder::<BodyDecoder<Utf8Decoder<RemainingBytesDecoder>>>::default();
        let item = track_try_unwrap!(
            decoder.decode_exact(b"HTTP/1.0 200 OK\r\nContent-Length: 6\r\n\r\nbarbaz".as_ref())
        );
        assert_eq!(
            item.to_string(),
            "HTTP/1.0 200 OK\r\nContent-Length: 6\r\n\r\nbarbaz"
        );
        assert_eq!(item.http_version(), HttpVersion::V1_0);
        assert_eq!(item.status_code().as_u16(), 200);
        assert_eq!(item.reason_phrase().as_str(), "OK");
        assert_eq!(
            item.header()
                .fields()
                .map(|f| (f.name().to_owned(), f.value().to_owned()))
                .collect::<Vec<_>>(),
            vec![("Content-Length".to_owned(), "6".to_owned())]
        );
        assert_eq!(item.body(), "barbaz");
    }
}