diff --git a/src/body.rs b/src/body.rs index 7348ac7..43fcfee 100644 --- a/src/body.rs +++ b/src/body.rs @@ -1,5 +1,4 @@ -use std::io::{Cursor, Read}; -use std::io; +use std::io::Read; use std::fs::File; use std::fmt; @@ -28,10 +27,18 @@ impl Body { */ } -impl Read for Body { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - self.reader.read(buf) - } +// useful for tests, but not publicly exposed +#[cfg(test)] +pub fn read_to_string(mut body: Body) -> ::std::io::Result { + let mut s = String::new(); + match body.reader { + Kind::Reader(ref mut reader, _) => { + reader.read_to_string(&mut s) + } + Kind::Bytes(ref mut bytes) => { + (&**bytes).read_to_string(&mut s) + } + }.map(|_| s) } enum Kind { @@ -39,28 +46,6 @@ enum Kind { Bytes(Vec), } -impl Read for Kind { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - match *self { - Kind::Reader(ref mut reader, _) => { - reader.read(buf) - } - Kind::Bytes(ref mut bytes) => { - // To make sure the bytes are removed properly when you read - // them, you need to use `drain()` - // FIXME: this will probably have poor performance for larger - // bodies due to allocating more than necessary. - let drained_bytes: Vec = bytes.drain(..).collect(); - - // then you need a Cursor because a standard Vec doesn't implement - // Read - let mut cursor = Cursor::new(drained_bytes); - cursor.read(buf) - } - } - } -} - impl From> for Body { #[inline] fn from(v: Vec) -> Body { diff --git a/src/client.rs b/src/client.rs index 24a51f3..5fd0319 100644 --- a/src/client.rs +++ b/src/client.rs @@ -291,11 +291,11 @@ impl Read for Response { #[cfg(test)] mod tests { use super::*; + use ::body; use hyper::method::Method; use hyper::Url; use hyper::header::{Host, Headers, ContentType}; use std::collections::HashMap; - use std::io::Read; use serde_urlencoded; use serde_json; @@ -378,8 +378,7 @@ mod tests { r = r.body(body); - let mut buf = String::new(); - r.body.unwrap().unwrap().read_to_string(&mut buf).unwrap(); + let buf = body::read_to_string(r.body.unwrap().unwrap()).unwrap(); assert_eq!(buf, body); } @@ -398,8 +397,7 @@ mod tests { // Make sure the content type was set assert_eq!(r.headers.get::(), Some(&ContentType::form_url_encoded())); - let mut buf = String::new(); - r.body.unwrap().unwrap().read_to_string(&mut buf).unwrap(); + let buf = body::read_to_string(r.body.unwrap().unwrap()).unwrap(); let body_should_be = serde_urlencoded::to_string(&form_data).unwrap(); assert_eq!(buf, body_should_be); @@ -419,8 +417,7 @@ mod tests { // Make sure the content type was set assert_eq!(r.headers.get::(), Some(&ContentType::json())); - let mut buf = String::new(); - r.body.unwrap().unwrap().read_to_string(&mut buf).unwrap(); + let buf = body::read_to_string(r.body.unwrap().unwrap()).unwrap(); let body_should_be = serde_json::to_string(&json_data).unwrap(); assert_eq!(buf, body_should_be);