http_body_util/combinators/
map_frame.rs1use bytes::Buf;
2use http_body::{Body, Frame};
3use pin_project_lite::pin_project;
4use std::{
5 any::type_name,
6 fmt,
7 pin::Pin,
8 task::{Context, Poll},
9};
10
11pin_project! {
12 #[derive(Clone, Copy)]
16 pub struct MapFrame<B, F> {
17 #[pin]
18 inner: B,
19 f: F
20 }
21}
22
23impl<B, F> MapFrame<B, F> {
24 #[inline]
25 pub(crate) fn new(body: B, f: F) -> Self {
26 Self { inner: body, f }
27 }
28
29 pub fn get_ref(&self) -> &B {
31 &self.inner
32 }
33
34 pub fn get_mut(&mut self) -> &mut B {
36 &mut self.inner
37 }
38
39 pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut B> {
41 self.project().inner
42 }
43
44 pub fn into_inner(self) -> B {
46 self.inner
47 }
48}
49
50impl<B, F, B2> Body for MapFrame<B, F>
51where
52 B: Body,
53 F: FnMut(Frame<B::Data>) -> Frame<B2>,
54 B2: Buf,
55{
56 type Data = B2;
57 type Error = B::Error;
58
59 fn poll_frame(
60 self: Pin<&mut Self>,
61 cx: &mut Context<'_>,
62 ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
63 let this = self.project();
64 match this.inner.poll_frame(cx) {
65 Poll::Pending => Poll::Pending,
66 Poll::Ready(None) => Poll::Ready(None),
67 Poll::Ready(Some(Ok(frame))) => Poll::Ready(Some(Ok((this.f)(frame)))),
68 Poll::Ready(Some(Err(err))) => Poll::Ready(Some(Err(err))),
69 }
70 }
71
72 fn is_end_stream(&self) -> bool {
73 self.inner.is_end_stream()
74 }
75}
76
77impl<B, F> fmt::Debug for MapFrame<B, F>
78where
79 B: fmt::Debug,
80{
81 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
82 f.debug_struct("MapFrame")
83 .field("inner", &self.inner)
84 .field("f", &type_name::<F>())
85 .finish()
86 }
87}