1use std::{
2 mem,
3 pin::Pin,
4 task::{Context, Poll},
5};
6
7use bytes::Bytes;
8use futures_core::Stream;
9use pin_project_lite::pin_project;
10
11use crate::error::PayloadError;
12
13pub type BoxedPayloadStream = Pin<Box<dyn Stream<Item = Result<Bytes, PayloadError>>>>;
15
16#[doc(hidden)]
17#[deprecated(since = "3.0.0", note = "Renamed to `BoxedPayloadStream`.")]
18pub type PayloadStream = BoxedPayloadStream;
19
20#[cfg(not(feature = "http2"))]
21pin_project! {
22 #[project = PayloadProj]
24 pub enum Payload<S = BoxedPayloadStream> {
25 None,
26 H1 { payload: crate::h1::Payload },
27 Stream { #[pin] payload: S },
28 }
29}
30
31#[cfg(feature = "http2")]
32pin_project! {
33 #[project = PayloadProj]
35 pub enum Payload<S = BoxedPayloadStream> {
36 None,
37 H1 { payload: crate::h1::Payload },
38 H2 { payload: crate::h2::Payload },
39 Stream { #[pin] payload: S },
40 }
41}
42
43impl_more::impl_enum_from!(<S> in crate::h1::Payload => Payload<S>::H1 { payload });
44#[cfg(feature = "http2")]
45impl_more::impl_enum_from!(<S> in crate::h2::Payload => Payload<S>::H2 { payload });
46impl_more::impl_enum_from!(BoxedPayloadStream => Payload::Stream { payload });
47
48impl<S> From<Bytes> for Payload<S> {
49 #[inline]
50 fn from(bytes: Bytes) -> Self {
51 let (_, mut pl) = crate::h1::Payload::create(true);
52 pl.unread_data(bytes);
53 self::Payload::from(pl)
54 }
55}
56
57impl<S> From<Vec<u8>> for Payload<S> {
58 #[inline]
59 fn from(vec: Vec<u8>) -> Self {
60 Payload::from(Bytes::from(vec))
61 }
62}
63
64#[cfg(feature = "http2")]
65impl<S> From<::h2::RecvStream> for Payload<S> {
66 #[inline]
67 fn from(stream: ::h2::RecvStream) -> Self {
68 Payload::H2 {
69 payload: crate::h2::Payload::new(stream),
70 }
71 }
72}
73
74impl<S> Payload<S> {
75 #[must_use]
77 pub fn take(&mut self) -> Payload<S> {
78 mem::replace(self, Payload::None)
79 }
80}
81
82impl<S> Stream for Payload<S>
83where
84 S: Stream<Item = Result<Bytes, PayloadError>>,
85{
86 type Item = Result<Bytes, PayloadError>;
87
88 #[inline]
89 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
90 match self.project() {
91 PayloadProj::None => Poll::Ready(None),
92 PayloadProj::H1 { payload } => Pin::new(payload).poll_next(cx),
93
94 #[cfg(feature = "http2")]
95 PayloadProj::H2 { payload } => Pin::new(payload).poll_next(cx),
96
97 PayloadProj::Stream { payload } => payload.poll_next(cx),
98 }
99 }
100}
101
102#[cfg(test)]
103mod tests {
104 use static_assertions::{assert_impl_all, assert_not_impl_any};
105
106 use super::*;
107
108 assert_impl_all!(Payload: Unpin);
109 assert_not_impl_any!(Payload: Send, Sync);
110}