Add extensions_ref() and extensions_mut() to req/resp builders (#403)

A similar capability already exists for many of the other `Parts` fields in these builders, and
is useful for the extensions map as well.
This commit is contained in:
Adam C. Foltzer
2020-03-25 11:19:15 -07:00
committed by GitHub
parent 3ee1b58295
commit 13a8a5734b
2 changed files with 70 additions and 0 deletions
+35
View File
@@ -976,6 +976,41 @@ impl Builder {
})
}
/// Get a reference to the extensions for this request builder.
///
/// If the builder has an error, this returns `None`.
///
/// # Example
///
/// ```
/// # use http::Request;
/// let req = Request::builder().extension("My Extension").extension(5u32);
/// let extensions = req.extensions_ref().unwrap();
/// assert_eq!(extensions.get::<&'static str>(), Some(&"My Extension"));
/// assert_eq!(extensions.get::<u32>(), Some(&5u32));
/// ```
pub fn extensions_ref(&self) -> Option<&Extensions> {
self.inner.as_ref().ok().map(|h| &h.extensions)
}
/// Get a mutable reference to the extensions for this request builder.
///
/// If the builder has an error, this returns `None`.
///
/// # Example
///
/// ```
/// # use http::Request;
/// let mut req = Request::builder().extension("My Extension");
/// let mut extensions = req.extensions_mut().unwrap();
/// assert_eq!(extensions.get::<&'static str>(), Some(&"My Extension"));
/// extensions.insert(5u32);
/// assert_eq!(extensions.get::<u32>(), Some(&5u32));
/// ```
pub fn extensions_mut(&mut self) -> Option<&mut Extensions> {
self.inner.as_mut().ok().map(|h| &mut h.extensions)
}
/// "Consumes" this builder, using the provided `body` to return a
/// constructed `Request`.
///
+35
View File
@@ -698,6 +698,41 @@ impl Builder {
})
}
/// Get a reference to the extensions for this response builder.
///
/// If the builder has an error, this returns `None`.
///
/// # Example
///
/// ```
/// # use http::Response;
/// let req = Response::builder().extension("My Extension").extension(5u32);
/// let extensions = req.extensions_ref().unwrap();
/// assert_eq!(extensions.get::<&'static str>(), Some(&"My Extension"));
/// assert_eq!(extensions.get::<u32>(), Some(&5u32));
/// ```
pub fn extensions_ref(&self) -> Option<&Extensions> {
self.inner.as_ref().ok().map(|h| &h.extensions)
}
/// Get a mutable reference to the extensions for this response builder.
///
/// If the builder has an error, this returns `None`.
///
/// # Example
///
/// ```
/// # use http::Response;
/// let mut req = Response::builder().extension("My Extension");
/// let mut extensions = req.extensions_mut().unwrap();
/// assert_eq!(extensions.get::<&'static str>(), Some(&"My Extension"));
/// extensions.insert(5u32);
/// assert_eq!(extensions.get::<u32>(), Some(&5u32));
/// ```
pub fn extensions_mut(&mut self) -> Option<&mut Extensions> {
self.inner.as_mut().ok().map(|h| &mut h.extensions)
}
/// "Consumes" this builder, using the provided `body` to return a
/// constructed `Response`.
///