| 1 | use bytes::Buf; |
| 2 | use http_body::{Body, Frame}; |
| 3 | use pin_project_lite::pin_project; |
| 4 | use std::{ |
| 5 | any::type_name, |
| 6 | fmt, |
| 7 | pin::Pin, |
| 8 | task::{Context, Poll}, |
| 9 | }; |
| 10 | |
| 11 | pin_project! { |
| 12 | /// Body returned by the [`map_frame`] combinator. |
| 13 | /// |
| 14 | /// [`map_frame`]: crate::BodyExt::map_frame |
| 15 | #[derive (Clone, Copy)] |
| 16 | pub struct MapFrame<B, F> { |
| 17 | #[pin] |
| 18 | inner: B, |
| 19 | f: F |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | impl<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 | /// Get a reference to the inner body |
| 30 | pub fn get_ref(&self) -> &B { |
| 31 | &self.inner |
| 32 | } |
| 33 | |
| 34 | /// Get a mutable reference to the inner body |
| 35 | pub fn get_mut(&mut self) -> &mut B { |
| 36 | &mut self.inner |
| 37 | } |
| 38 | |
| 39 | /// Get a pinned mutable reference to the inner body |
| 40 | pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut B> { |
| 41 | self.project().inner |
| 42 | } |
| 43 | |
| 44 | /// Consume `self`, returning the inner body |
| 45 | pub fn into_inner(self) -> B { |
| 46 | self.inner |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | impl<B, F, B2> Body for MapFrame<B, F> |
| 51 | where |
| 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: Projection<'_, B, F> = 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: Frame<::Data>))) => Poll::Ready(Some(Ok((this.f)(frame)))), |
| 68 | Poll::Ready(Some(Err(err: ::Error))) => Poll::Ready(Some(Err(err))), |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | fn is_end_stream(&self) -> bool { |
| 73 | self.inner.is_end_stream() |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | impl<B, F> fmt::Debug for MapFrame<B, F> |
| 78 | where |
| 79 | B: fmt::Debug, |
| 80 | { |
| 81 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 82 | f&mut DebugStruct<'_, '_>.debug_struct("MapFrame" ) |
| 83 | .field("inner" , &self.inner) |
| 84 | .field(name:"f" , &type_name::<F>()) |
| 85 | .finish() |
| 86 | } |
| 87 | } |
| 88 | |