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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
use std;

use futures::Future;
use futures::Stream;
use hina;
use hyper::Error as HyperError;
use hyper::Headers;
use hyper::Response;
use hyper::StatusCode;
use hyper::header::ContentLength;

use simplist::HttpError;



/// a http response, whose body can be read asynchronously.
///
/// there are two primary methods to retrieve the body for a response:
///
///   - [`fn read_as_bytes(...)`](struct.HttpResponse.html#method.read_as_bytes): returns a future that will resolve to
///     a [`Vec<u8>`](https://doc.rust-lang.org/std/vec/struct.Vec.html) that contains the response body.
///   - [`fn read_as_string(...)`](struct.HttpResponse.html#method.read_as_string): returns a future that will resolve
///     to a [`String`](https://doc.rust-lang.org/std/string/struct.String.html) that contains the response body.
///
/// # usage
///
/// instances of this struct are returned by invoking one of the
/// [`HttpClient::request`](struct.HttpClient.html#method.request)'s methods.
///
/// ```
/// use simplist::HttpClient;
/// use simplist::HttpMethod;
/// use simplist::HttpRequest;
///
/// let url      = "https://hinaria.com".parse()?;
/// let http     = HttpClient::new(...);
/// let request  = HttpRequest::with(url, HttpMethod::Get);
/// let response = await http.request(request)?;
/// let string   = await response.read_as_string();
///
/// println!("{:?}", string)
/// // => Ok("<!doctype html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"utf-8\"> ...")
/// ```
pub struct HttpResponse {
    underlying: Response,
}

impl HttpResponse {
    pub(crate) fn new(underlying: Response) -> HttpResponse {
        HttpResponse { underlying }
    }

    /// returns the http headers for this response.
    ///
    /// # examples
    ///
    /// ```
    /// use hyper::Headers;
    /// use simplist::HttpClient;
    /// use simplist::HttpMethod;
    /// use simplist::HttpRequest;
    ///
    /// let url      = "https://hinaria.com".parse()?;
    /// let http     = HttpClient::new(...);
    /// let request  = HttpRequest::with(url, HttpMethod::Get);
    /// let response = await http.request(request)?;
    /// let headers  = response.headers();
    ///
    /// assert_eq!(headers.has::<ContentType>(), true);
    /// ```
    pub fn headers(&self) -> &Headers {
        self.underlying.headers()
    }

    /// returns the status code for this response.
    ///
    /// # examples
    ///
    /// ```
    /// use hyper::status::StatusCode;
    /// use simplist::HttpClient;
    /// use simplist::HttpMethod;
    /// use simplist::HttpRequest;
    ///
    /// let url      = "https://hinaria.com".parse()?;
    /// let http     = HttpClient::new(...);
    /// let request  = HttpRequest::with(url, HttpMethod::Get);
    /// let response = await http.request(request)?;
    ///
    /// assert_eq!(response.status(), StatusCode::Ok);
    /// ```
    pub fn status(&self) -> StatusCode {
        self.underlying.status()
    }

    /// returns the status code for as a `u16`.
    ///
    /// # examples
    ///
    /// ```
    /// use simplist::HttpClient;
    /// use simplist::HttpMethod;
    /// use simplist::HttpRequest;
    ///
    /// let url      = "https://hinaria.com".parse()?;
    /// let http     = HttpClient::new(...);
    /// let request  = HttpRequest::with(url, HttpMethod::Get);
    /// let response = await http.request(request)?;
    ///
    /// assert_eq!(response.status_code(), 200);
    /// ```
    pub fn status_code(&self) -> u16 {
        self.underlying.status().into()
    }

    /// reads this response, returning a [`Vec<u8>`](https://doc.rust-lang.org/std/vec/struct.Vec.html).
    ///
    /// # examples
    ///
    /// ```
    /// use simplist::HttpClient;
    /// use simplist::HttpMethod;
    /// use simplist::HttpRequest;
    ///
    /// let url      = "https://hinaria.com".parse()?;
    /// let http     = HttpClient::new(...);
    /// let request  = HttpRequest::with(url, HttpMethod::Get);
    /// let response = await http.request(request)?;
    /// let data     = await response.read_as_bytes();
    ///
    /// println!("{:?}", data)
    /// // => Ok([60, 33, 68, 79, 67, 84, 89, 80, 69, 32, 104, 116, ...])
    /// ```
    pub fn read_as_bytes(self) -> Box<Future<Item = Vec<u8>, Error = HttpError>> {
        const READ_DEFAULT_CAPACITY:     usize = 10 * 1024;        // 10 kib
        const READ_MAX_INITIAL_CAPACITY: usize = 10 * 1024 * 1024; // 10 mib


        let capacity = self.underlying.headers()
            .get::<ContentLength>()
            .map      (|x| std::cmp::max(x.0 as usize, READ_MAX_INITIAL_CAPACITY))
            .unwrap_or(READ_DEFAULT_CAPACITY);

        let future = self.underlying.body().fold(
            Vec::with_capacity(capacity),
            |mut data, chunk| { data.extend(chunk); hina::task::completed::<_, HyperError>(data) }
        ).map_err(From::from);

        Box::new(future)
    }

    /// reads this response, returning a [`String`](https://doc.rust-lang.org/std/string/struct.String.html).
    ///
    /// # examples
    ///
    /// ```
    /// use simplist::HttpClient;
    /// use simplist::HttpMethod;
    /// use simplist::HttpRequest;
    ///
    /// let url      = "https://hinaria.com".parse()?;
    /// let http     = HttpClient::new(...);
    /// let request  = HttpRequest::with(url, HttpMethod::Get);
    /// let response = await http.request(request)?;
    /// let string   = await response.read_as_string();
    ///
    /// println!("{:?}", string)
    /// // => Ok("<!doctype html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"utf-8\"> ...")
    /// ```
    pub fn read_as_string(self) -> Box<Future<Item = String, Error = HttpError>> {
        let future = self
            .read_as_bytes()
            .and_then     (|x| String::from_utf8(x).map_err(From::from));

        Box::new(future)
    }
}





/// a http response, whose body can be read synchronously.
///
/// there are two primary methods to retrieve the body for a response:
///
///   - [`fn read_as_bytes(...)`](struct.HttpSyncResponse.html#method.read_as_bytes): returns a [`Result<Vec<u8>,
///     HttpError>`](https://doc.rust-lang.org/std/vec/struct.Vec.html) that contains the response body.
///   - [`fn read_as_string(...)`](struct.HttpSyncResponse.html#method.read_as_string): returns a [`Result<String,
///     HttpError>`](https://doc.rust-lang.org/std/string/struct.String.html) that contains the response
///     body.
///
/// # usage
///
/// instances of this struct are returned by invoking one of the
/// [`HttpSyncClient::request`](struct.HttpSyncClient.html#method.request)'s methods.
///
/// ```
/// use simplist::HttpMethod;
/// use simplist::HttpResponse;
/// use simplist::HttpSyncClient;
///
/// let url      = "https://hinaria.com".parse()?;
/// let http     = HttpSyncClient::new(...);
/// let request  = HttpRequest::with(url, HttpMethod::Get);
/// let response = http.request(request)?;
/// let string   = response.read_as_string();
///
/// println!("{:?}", string)
/// // => Ok("<!doctype html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"utf-8\"> ...")
/// ```
pub struct HttpSyncResponse {
    underlying: HttpResponse,
}

impl HttpSyncResponse {
    pub(crate) fn new(underlying: HttpResponse) -> HttpSyncResponse {
        HttpSyncResponse { underlying }
    }

    /// returns the http headers for this response.
    ///
    /// # examples
    ///
    /// ```
    /// use hyper::Headers;
    /// use simplist::HttpSyncClient;
    /// use simplist::HttpMethod;
    /// use simplist::HttpRequest;
    ///
    /// let url      = "https://hinaria.com".parse()?;
    /// let http     = HttpSyncClient::new(...);
    /// let request  = HttpRequest::with(url, HttpMethod::Get);
    /// let response = await http.request(request)?;
    /// let headers  = response.headers();
    ///
    /// assert_eq!(headers.has::<ContentType>(), true);
    /// ```
    pub fn headers(&self) -> &Headers {
        self.underlying.headers()
    }

    /// returns the status code for this response.
    ///
    /// # examples
    ///
    /// ```
    /// use hyper::status::StatusCode;
    /// use simplist::HttpMethod;
    /// use simplist::HttpRequest;
    /// use simplist::HttpSyncClient;
    ///
    /// let url      = "https://hinaria.com".parse()?;
    /// let http     = HttpSyncClient::new(...);
    /// let request  = HttpRequest::with(url, HttpMethod::Get);
    /// let response = http.request(request)?;
    ///
    /// assert_eq!(response.status(), StatusCode::Ok);
    /// ```
    pub fn status(&self) -> StatusCode {
        self.underlying.status()
    }

    /// returns the status code for as a `u16`.
    ///
    /// # examples
    ///
    /// ```
    /// use simplist::HttpMethod;
    /// use simplist::HttpRequest;
    /// use simplist::HttpSyncClient;
    ///
    /// let url      = "https://hinaria.com".parse()?;
    /// let http     = HttpSyncClient::new(...);
    /// let request  = HttpRequest::with(url, HttpMethod::Get);
    /// let response = http.request(request)?;
    ///
    /// assert_eq!(response.status_code(), 200);
    /// ```
    pub fn status_code(&self) -> u16 {
        self.underlying.status_code()
    }

    /// reads this response, returning a [`Vec<u8>`](https://doc.rust-lang.org/std/vec/struct.Vec.html).
    ///
    /// # examples
    ///
    /// ```
    /// use simplist::HttpMethod;
    /// use simplist::HttpRequest;
    /// use simplist::HttpSyncClient;
    ///
    /// let url      = "https://hinaria.com".parse()?;
    /// let http     = HttpSyncClient::new(...);
    /// let request  = HttpRequest::with(url, HttpMethod::Get);
    /// let response = http.request(request)?;
    /// let data     = await response.read_as_bytes();
    ///
    /// println!("{:?}", data)
    /// // => Ok([60, 33, 68, 79, 67, 84, 89, 80, 69, 32, 104, 116, ...])
    /// ```
    pub fn read_as_bytes(self) -> Result<Vec<u8>, HttpError> {
        self.underlying.read_as_bytes().wait()
    }

    /// reads this response, returning a [`String`](https://doc.rust-lang.org/std/string/struct.String.html).
    ///
    /// # examples
    ///
    /// ```
    /// use simplist::HttpMethod;
    /// use simplist::HttpRequest;
    /// use simplist::HttpSyncClient;
    ///
    /// let url      = "https://hinaria.com".parse()?;
    /// let http     = HttpSyncClient::new(...);
    /// let request  = HttpRequest::with(url, HttpMethod::Get);
    /// let response = http.request(request)?;
    /// let string   = response.read_as_string();
    ///
    /// println!("{:?}", string)
    /// // => Ok("<!doctype html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"utf-8\"> ...")
    /// ```
    pub fn read_as_string(self) -> Result<String, HttpError> {
        self.underlying.read_as_string().wait()
    }
}