1use std::task::{Context, Poll};
2use std::{cell::RefCell, ops::Deref, pin::Pin, rc::Rc};
3
4use crate::channel::bstream::{self, Receiver};
5use crate::http::{HeaderMap, error::PayloadError};
6use crate::util::{Bytes, Stream};
7
8#[derive(Debug)]
21pub struct Payload {
22 rx: Receiver<PayloadError>,
23 trailers: Rc<RefCell<Option<HeaderMap>>>,
24}
25
26impl Payload {
27 pub(crate) fn create() -> (PayloadSender, Payload) {
29 let (tx, rx) = bstream::channel();
30 let trailers = Rc::new(RefCell::new(None));
31 (
32 PayloadSender {
33 tx,
34 trailers: trailers.clone(),
35 },
36 Payload { rx, trailers },
37 )
38 }
39
40 pub fn trailers(&self) -> Option<HeaderMap> {
45 self.trailers.borrow().clone()
46 }
47
48 pub fn take_trailers(&self) -> Option<HeaderMap> {
52 self.trailers.borrow_mut().take()
53 }
54}
55
56impl From<Receiver<PayloadError>> for Payload {
57 fn from(rx: Receiver<PayloadError>) -> Self {
58 Payload {
59 rx,
60 trailers: Rc::default(),
61 }
62 }
63}
64
65impl Deref for Payload {
66 type Target = Receiver<PayloadError>;
67
68 fn deref(&self) -> &Self::Target {
69 &self.rx
70 }
71}
72
73impl Stream for Payload {
74 type Item = Result<Bytes, PayloadError>;
75
76 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
77 self.rx.poll_read(cx)
78 }
79}
80
81#[derive(Debug)]
83pub(crate) struct PayloadSender {
84 tx: bstream::Sender<PayloadError>,
85 trailers: Rc<RefCell<Option<HeaderMap>>>,
86}
87
88impl PayloadSender {
89 pub(crate) fn feed_trailers(&self, trailers: HeaderMap) {
91 *self.trailers.borrow_mut() = Some(trailers);
92 }
93}
94
95impl Deref for PayloadSender {
96 type Target = bstream::Sender<PayloadError>;
97
98 fn deref(&self) -> &Self::Target {
99 &self.tx
100 }
101}