qiniu_multipart/client/
sized.rs

1// Copyright 2016 `multipart` Crate Developers
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7//! Sized/buffered wrapper around `HttpRequest`.
8
9use client::{HttpRequest, HttpStream};
10
11use std::io;
12use std::io::prelude::*;
13
14/// A wrapper around a request object that measures the request body and sets the `Content-Length`
15/// header to its size in bytes.
16///
17/// Sized requests are more human-readable and use less bandwidth 
18/// (as chunking adds [visual noise and overhead][chunked-example]),
19/// but they must be able to load their entirety, including the contents of all files
20/// and streams, into memory so the request body can be measured.
21///
22/// You should really only use sized requests if you intend to inspect the data manually on the
23/// server side, as it will produce a more human-readable request body. Also, of course, if the
24/// server doesn't support chunked requests or otherwise rejects them. 
25///
26/// [chunked-example]: http://en.wikipedia.org/wiki/Chunked_transfer_encoding#Example 
27pub struct SizedRequest<R> {
28    inner: R,
29    buffer: Vec<u8>,
30    boundary: String,
31}
32
33impl<R: HttpRequest> SizedRequest<R> {
34    #[doc(hidden)]
35    pub fn from_request(req: R) -> SizedRequest<R> {
36        SizedRequest {
37            inner: req,
38            buffer: Vec::new(),
39            boundary: String::new(),
40        }
41    }
42}
43
44impl<R> Write for SizedRequest<R> {
45    fn write(&mut self, data: &[u8]) -> io::Result<usize> {
46        self.buffer.write(data)
47    }
48
49    fn flush(&mut self) -> io::Result<()> { Ok(()) }
50}
51
52impl<R: HttpRequest> HttpRequest for SizedRequest<R> 
53where <R::Stream as HttpStream>::Error: From<R::Error> {
54    type Stream = Self;
55    type Error = R::Error;
56
57    /// `SizedRequest` ignores `_content_len` because it sets its own later.
58    fn apply_headers(&mut self, boundary: &str, _content_len: Option<u64>) -> bool {
59        self.boundary.clear();
60        self.boundary.push_str(boundary);
61        true
62    }
63
64    fn open_stream(mut self) -> Result<Self, Self::Error> {
65        self.buffer.clear();
66        Ok(self)
67    }
68}
69
70impl<R: HttpRequest> HttpStream for SizedRequest<R> 
71where <R::Stream as HttpStream>::Error: From<R::Error> { 
72    type Request = Self;
73    type Response = <<R as HttpRequest>::Stream as HttpStream>::Response;
74    type Error = <<R as HttpRequest>::Stream as HttpStream>::Error;
75
76    fn finish(mut self) -> Result<Self::Response, Self::Error> {
77        let content_len = self.buffer.len() as u64;
78        
79        if !self.inner.apply_headers(&self.boundary, Some(content_len)) {
80            return Err(io::Error::new(
81                io::ErrorKind::Other, 
82                "SizedRequest failed to apply headers to wrapped request."
83            ).into());
84        }
85
86        let mut req = self.inner.open_stream()?;
87        io::copy(&mut &self.buffer[..], &mut req)?;
88        req.finish()
89    }
90}