From 5f02b4d21b4567ff4ba97ed8fb89f6dd588f9aee Mon Sep 17 00:00:00 2001 From: Kevin Choubacha Date: Thu, 4 Jan 2018 10:59:02 -0800 Subject: [PATCH] Add a `map` to Request and Response (#151) For ease of use, it's nice to be able to map using a closure from one type to another. This adds that ability to both the `Request` and `Response` objects. --- src/request.rs | 36 ++++++++++++++++++++++++++++++++++++ src/response.rs | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+) diff --git a/src/request.rs b/src/request.rs index 2405eba..939c1c4 100644 --- a/src/request.rs +++ b/src/request.rs @@ -638,6 +638,27 @@ impl Request { pub fn into_parts(self) -> (Parts, T) { (self.head, self.body) } + + /// Consumes the request returning a new request with body mapped to the + /// return type of the passed in function. + /// + /// # Examples + /// + /// ``` + /// # use http::*; + /// let request = Request::builder().body("some string").unwrap(); + /// let mapped_request: Request<&[u8]> = request.map(|b| { + /// assert_eq!(b, "some string"); + /// b.as_bytes() + /// }); + /// assert_eq!(mapped_request.body(), &"some string".as_bytes()); + /// ``` + #[inline] + pub fn map(self, f: F) -> Request + where F: FnOnce(T) -> U + { + Request { body: f(self.body), head: self.head } + } } impl Default for Request { @@ -906,3 +927,18 @@ impl Default for Builder { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn it_can_map_a_body_from_one_type_to_another() { + let request= Request::builder().body("some string").unwrap(); + let mapped_request = request.map(|s| { + assert_eq!(s, "some string"); + 123u32 + }); + assert_eq!(mapped_request.body(), &123u32); + } +} diff --git a/src/response.rs b/src/response.rs index 29ca208..79d6700 100644 --- a/src/response.rs +++ b/src/response.rs @@ -439,6 +439,27 @@ impl Response { pub fn into_parts(self) -> (Parts, T) { (self.head, self.body) } + + /// Consumes the response returning a new response with body mapped to the + /// return type of the passed in function. + /// + /// # Examples + /// + /// ``` + /// # use http::*; + /// let response = Response::builder().body("some string").unwrap(); + /// let mapped_response: Response<&[u8]> = response.map(|b| { + /// assert_eq!(b, "some string"); + /// b.as_bytes() + /// }); + /// assert_eq!(mapped_response.body(), &"some string".as_bytes()); + /// ``` + #[inline] + pub fn map(self, f: F) -> Response + where F: FnOnce(T) -> U + { + Response { body: f(self.body), head: self.head } + } } impl Default for Response { @@ -676,3 +697,18 @@ impl Default for Builder { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn it_can_map_a_body_from_one_type_to_another() { + let response = Response::builder().body("some string").unwrap(); + let mapped_response = response.map(|s| { + assert_eq!(s, "some string"); + 123u32 + }); + assert_eq!(mapped_response.body(), &123u32); + } +}