use std::task::{Context, Poll};
use std::{cell::RefCell, ops::Deref, pin::Pin, rc::Rc};
use crate::channel::bstream::{self, Receiver};
use crate::http::{HeaderMap, error::PayloadError};
use crate::util::{Bytes, Stream};
#[derive(Debug)]
pub struct Payload {
rx: Receiver<PayloadError>,
trailers: Rc<RefCell<Option<HeaderMap>>>,
}
impl Payload {
pub(crate) fn create() -> (PayloadSender, Payload) {
let (tx, rx) = bstream::channel();
let trailers = Rc::new(RefCell::new(None));
(
PayloadSender {
tx,
trailers: trailers.clone(),
},
Payload { rx, trailers },
)
}
pub fn trailers(&self) -> Option<HeaderMap> {
self.trailers.borrow().clone()
}
}
impl From<Receiver<PayloadError>> for Payload {
fn from(rx: Receiver<PayloadError>) -> Self {
Payload {
rx,
trailers: Rc::default(),
}
}
}
impl Deref for Payload {
type Target = Receiver<PayloadError>;
fn deref(&self) -> &Self::Target {
&self.rx
}
}
impl Stream for Payload {
type Item = Result<Bytes, PayloadError>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.rx.poll_read(cx)
}
}
#[derive(Debug)]
pub(crate) struct PayloadSender {
tx: bstream::Sender<PayloadError>,
trailers: Rc<RefCell<Option<HeaderMap>>>,
}
impl PayloadSender {
pub(crate) fn feed_trailers(&self, trailers: HeaderMap) {
*self.trailers.borrow_mut() = Some(trailers);
}
}
impl Deref for PayloadSender {
type Target = bstream::Sender<PayloadError>;
fn deref(&self) -> &Self::Target {
&self.tx
}
}