mas_http/layers/
bytes_to_body_request.rs

1// Copyright 2022 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use bytes::Bytes;
16use http::Request;
17use http_body_util::Full;
18use tower::{Layer, Service};
19
20#[derive(Clone)]
21pub struct BytesToBodyRequest<S> {
22    inner: S,
23}
24
25impl<S> BytesToBodyRequest<S> {
26    pub const fn new(inner: S) -> Self {
27        Self { inner }
28    }
29}
30
31impl<S> Service<Request<Bytes>> for BytesToBodyRequest<S>
32where
33    S: Service<Request<Full<Bytes>>>,
34    S::Future: Send + 'static,
35{
36    type Error = S::Error;
37    type Response = S::Response;
38    type Future = S::Future;
39
40    fn poll_ready(
41        &mut self,
42        cx: &mut std::task::Context<'_>,
43    ) -> std::task::Poll<Result<(), Self::Error>> {
44        self.inner.poll_ready(cx)
45    }
46
47    fn call(&mut self, request: Request<Bytes>) -> Self::Future {
48        let (parts, body) = request.into_parts();
49        let body = Full::new(body);
50
51        let request = Request::from_parts(parts, body);
52
53        self.inner.call(request)
54    }
55}
56
57#[derive(Default, Clone, Copy)]
58pub struct BytesToBodyRequestLayer;
59
60impl<S> Layer<S> for BytesToBodyRequestLayer {
61    type Service = BytesToBodyRequest<S>;
62
63    fn layer(&self, inner: S) -> Self::Service {
64        BytesToBodyRequest::new(inner)
65    }
66}