use std::{
pin::Pin,
task::{Context, Poll},
};
use futures_util::Stream;
use tokio::sync::mpsc;
#[derive(Debug)]
pub struct Receiver<T> {
rx: mpsc::Receiver<T>,
}
impl<T> Receiver<T> {
pub fn new(rx: mpsc::Receiver<T>) -> Self {
Self { rx }
}
pub fn try_next(&mut self) -> Option<T> {
self.rx.try_recv().ok()
}
pub fn drain(&mut self) -> impl Iterator<Item = T> + '_ {
struct Iter<'a, T>(&'a mut Receiver<T>);
impl<'a, T> Iterator for Iter<'a, T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
self.0.try_next()
}
}
Iter(self)
}
}
impl<T> Stream for Receiver<T> {
type Item = T;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.rx.poll_recv(cx)
}
}