http_body_request_validator/
http_body_util.rs

1//! The [`http-body-util`]-powered bufferer.
2
3/// The bufferer that uses [`http_body_util`] implementation that aggregates into [`bytes::Bytes`].
4#[derive(Debug, Copy)]
5pub struct Bufferer<Data>(core::marker::PhantomData<Data>);
6
7impl<Data> Bufferer<Data> {
8    /// Create a new [`Bufferer`] instance.
9    pub const fn new() -> Self {
10        Self(core::marker::PhantomData)
11    }
12}
13
14impl<Data> Default for Bufferer<Data> {
15    fn default() -> Self {
16        Self::new()
17    }
18}
19
20impl<Data> Clone for Bufferer<Data> {
21    fn clone(&self) -> Self {
22        Self::new()
23    }
24}
25
26impl<InBody> super::Bufferer<InBody> for Bufferer<bytes::Bytes>
27where
28    InBody: http_body::Body,
29{
30    type Buffered = crate::buffered::Buffered<bytes::Bytes>;
31    type Error = <InBody as http_body::Body>::Error;
32
33    async fn buffer(&self, body: InBody) -> Result<Self::Buffered, Self::Error> {
34        let collected_body = http_body_util::BodyExt::collect(body).await?;
35        let trailers = collected_body.trailers().cloned();
36        let data = collected_body.to_bytes();
37        Ok(crate::buffered::Buffered { data, trailers })
38    }
39}
40
41/// The boxed [`bytes::Buf`].
42#[cfg(feature = "alloc")]
43pub type BoxBuf = alloc::boxed::Box<dyn bytes::Buf>;
44
45#[cfg(feature = "alloc")]
46impl<InBody> super::Bufferer<InBody> for Bufferer<BoxBuf>
47where
48    InBody: http_body::Body,
49    <InBody as http_body::Body>::Data: 'static,
50{
51    type Buffered = crate::buffered::Buffered<BoxBuf>;
52    type Error = <InBody as http_body::Body>::Error;
53
54    async fn buffer(&self, body: InBody) -> Result<Self::Buffered, Self::Error> {
55        let collected_body = http_body_util::BodyExt::collect(body).await?;
56        let trailers = collected_body.trailers().cloned();
57        let data = alloc::boxed::Box::new(collected_body.aggregate());
58        Ok(crate::buffered::Buffered { data, trailers })
59    }
60}