Skip to main content

rama_http_hyperium/into_rama/
message.rs

1//! Message conversions (request, response, and their parts).
2
3use rama_core::extensions::{Extensions, ExtensionsRef as _};
4use rama_http_types::{Request, Response, request, response};
5
6use super::TryIntoRamaHttp;
7use crate::HyperExtensions;
8
9impl<T> TryIntoRamaHttp for http::Request<T> {
10    type Output = Request<T>;
11    type Error = rama_http_types::Error;
12
13    fn try_into_rama_http(self) -> Result<Request<T>, rama_http_types::Error> {
14        let (mut parts, body) = self.into_parts();
15        // Pull any previously-stashed rama extensions back out; stash the
16        // remaining http extensions so a later rama → http hop restores them.
17        let rama_extensions = parts.extensions.remove::<Extensions>().unwrap_or_default();
18        rama_extensions.insert(HyperExtensions(parts.extensions));
19
20        let mut req = Request::new(body);
21        *req.method_mut() = parts.method.try_into_rama_http()?;
22        *req.uri_mut() = parts.uri.try_into_rama_http()?;
23        *req.version_mut() = parts.version.try_into_rama_http()?;
24        *req.headers_mut() = parts.headers.try_into_rama_http()?;
25        req.extensions().extend(&rama_extensions);
26        Ok(req)
27    }
28}
29
30impl<T> TryIntoRamaHttp for http::Response<T> {
31    type Output = Response<T>;
32    type Error = rama_http_types::Error;
33
34    fn try_into_rama_http(self) -> Result<Response<T>, rama_http_types::Error> {
35        let (mut parts, body) = self.into_parts();
36        let rama_extensions = parts.extensions.remove::<Extensions>().unwrap_or_default();
37        rama_extensions.insert(HyperExtensions(parts.extensions));
38
39        let mut res = Response::new(body);
40        *res.status_mut() = parts.status.try_into_rama_http()?;
41        *res.version_mut() = parts.version.try_into_rama_http()?;
42        *res.headers_mut() = parts.headers.try_into_rama_http()?;
43        res.extensions().extend(&rama_extensions);
44        Ok(res)
45    }
46}
47
48impl TryIntoRamaHttp for http::request::Parts {
49    type Output = request::Parts;
50    type Error = rama_http_types::Error;
51
52    fn try_into_rama_http(self) -> Result<request::Parts, rama_http_types::Error> {
53        // `request::Parts::new` is private + non-exhaustive, so route through a
54        // `Request<()>` and split it back out.
55        Ok(http::Request::from_parts(self, ())
56            .try_into_rama_http()?
57            .into_parts()
58            .0)
59    }
60}
61
62impl TryIntoRamaHttp for http::response::Parts {
63    type Output = response::Parts;
64    type Error = rama_http_types::Error;
65
66    fn try_into_rama_http(self) -> Result<response::Parts, rama_http_types::Error> {
67        Ok(http::Response::from_parts(self, ())
68            .try_into_rama_http()?
69            .into_parts()
70            .0)
71    }
72}