Use lifetimes for more elements of Payload

Text and Bytes can both have their lifetimes parameterized.
This commit is contained in:
Jacob Hoffman-Andrews
2020-10-25 15:52:02 -07:00
parent c8cd130770
commit 17ab5110a3
2 changed files with 12 additions and 7 deletions

View File

@@ -17,11 +17,11 @@ use super::SerdeValue;
/// *Internal API* /// *Internal API*
pub(crate) enum Payload<'a> { pub(crate) enum Payload<'a> {
Empty, Empty,
Text(String, String), Text(&'a str, String),
#[cfg(feature = "json")] #[cfg(feature = "json")]
JSON(SerdeValue), JSON(SerdeValue),
Reader(Box<dyn Read + 'a>), Reader(Box<dyn Read + 'a>),
Bytes(Vec<u8>), Bytes(&'a [u8]),
} }
impl fmt::Debug for Payload<'_> { impl fmt::Debug for Payload<'_> {
@@ -86,7 +86,7 @@ impl<'a> Payload<'a> {
encoding.encode(&text, EncoderTrap::Replace).unwrap() encoding.encode(&text, EncoderTrap::Replace).unwrap()
}; };
#[cfg(not(feature = "charset"))] #[cfg(not(feature = "charset"))]
let bytes = text.into_bytes(); let bytes = text.as_bytes();
let len = bytes.len(); let len = bytes.len();
let cursor = Cursor::new(bytes); let cursor = Cursor::new(bytes);
SizedReader::new(BodySize::Known(len as u64), Box::new(cursor)) SizedReader::new(BodySize::Known(len as u64), Box::new(cursor))

View File

@@ -153,7 +153,7 @@ impl Request {
/// println!("{:?}", r); /// println!("{:?}", r);
/// ``` /// ```
pub fn send_bytes(&mut self, data: &[u8]) -> Response { pub fn send_bytes(&mut self, data: &[u8]) -> Response {
self.do_call(Payload::Bytes(data.to_owned())) self.do_call(Payload::Bytes(data))
} }
/// Send data as a string. /// Send data as a string.
@@ -178,10 +178,9 @@ impl Request {
/// println!("{:?}", r); /// println!("{:?}", r);
/// ``` /// ```
pub fn send_string(&mut self, data: &str) -> Response { pub fn send_string(&mut self, data: &str) -> Response {
let text = data.into();
let charset = let charset =
crate::response::charset_from_content_type(self.header("content-type")).to_string(); crate::response::charset_from_content_type(self.header("content-type")).to_string();
self.do_call(Payload::Text(text, charset)) self.do_call(Payload::Text(data, charset))
} }
/// Send a sequence of (key, value) pairs as form-urlencoded data. /// Send a sequence of (key, value) pairs as form-urlencoded data.
@@ -206,7 +205,7 @@ impl Request {
let encoded = form_urlencoded::Serializer::new(String::new()) let encoded = form_urlencoded::Serializer::new(String::new())
.extend_pairs(data) .extend_pairs(data)
.finish(); .finish();
self.do_call(Payload::Bytes(encoded.into_bytes())) self.do_call(Payload::Bytes(&encoded.into_bytes()))
} }
/// Send data from a reader. /// Send data from a reader.
@@ -668,3 +667,9 @@ fn no_hostname() {
); );
assert!(req.get_host().is_err()); assert!(req.get_host().is_err());
} }
#[test]
fn send_byte_slice() {
let bytes = vec![1, 2, 3];
crate::agent().post("http://example.com").send(&bytes[1..2]);
}