http_body_request_validator/
buffered.rs

1//! Types for storing buffered body data.
2//!
3//! If the provided types don't fir the implementation for whatever reason it is easy to implement
4//! your own.
5
6/// Buffered body parts.
7///
8/// Intended to represent.
9pub struct Buffered<Data: bytes::Buf> {
10    /// The body data.
11    ///
12    /// Must be viewable as a [`bytes::Buf`].
13    pub data: Data,
14
15    /// The buffered trailers, if any.
16    pub trailers: Option<http::HeaderMap>,
17}
18
19impl<Data: bytes::Buf> super::AsBuf for Buffered<Data> {
20    type Data = Data;
21
22    fn as_buf(&self) -> &Self::Data {
23        &self.data
24    }
25}
26
27pin_project_lite::pin_project! {
28    /// Buffered body implementation.
29    pub struct Body<Data: bytes::Buf> {
30        data: Option<Data>,
31        trailers: Option<http::HeaderMap>,
32    }
33}
34
35impl<Data: bytes::Buf> Body<Data> {
36    /// Create a buffered [`Body`] from [`Buffered`].
37    pub fn from_buffered(value: Buffered<Data>) -> Self {
38        Self {
39            data: Some(value.data),
40            trailers: value.trailers,
41        }
42    }
43}
44
45impl<Data: bytes::Buf> crate::convert::IntoBody for Buffered<Data> {
46    type Body = Body<Data>;
47
48    fn into_body(self) -> Self::Body {
49        Body::from_buffered(self)
50    }
51}
52
53impl<Data: bytes::Buf> http_body::Body for Body<Data> {
54    type Data = Data;
55    type Error = core::convert::Infallible;
56
57    fn poll_frame(
58        self: core::pin::Pin<&mut Self>,
59        _cx: &mut core::task::Context<'_>,
60    ) -> core::task::Poll<Option<Result<http_body::Frame<Self::Data>, Self::Error>>> {
61        let this = self.project();
62
63        let frame = if let Some(data) = this.data.take() {
64            http_body::Frame::data(data)
65        } else if let Some(trailers) = this.trailers.take() {
66            http_body::Frame::trailers(trailers)
67        } else {
68            return core::task::Poll::Ready(None);
69        };
70
71        core::task::Poll::Ready(Some(Ok(frame)))
72    }
73}