use core::fmt;
use core::future::poll_fn;
use core::task::{Context, Poll};
use super::bounded::Bounded;
use super::chan::Chan;
use super::error::TryRecvError;
use crate::sync::internal::{self, Arc};
pub struct Receiver<T> {
chan: Arc<Chan<T, Bounded>>,
}
impl<T> Receiver<T> {
pub(super) fn new(chan: Arc<Chan<T, Bounded>>) -> Self {
Self { chan }
}
pub async fn recv(&mut self) -> Option<T> {
poll_fn(|cx| self.poll_recv(cx)).await
}
pub async fn recv_many(&mut self, buffer: &mut Vec<T>, limit: usize) -> usize {
poll_fn(|cx| self.poll_recv_many(cx, buffer, limit)).await
}
pub fn try_recv(&mut self) -> Result<T, TryRecvError> {
unsafe { self.chan.try_recv() }
}
pub fn blocking_recv(&mut self) -> Option<T> {
internal::blocking(self.recv())
}
pub fn blocking_recv_many(&mut self, buffer: &mut Vec<T>, limit: usize) -> usize {
internal::blocking(self.recv_many(buffer, limit))
}
pub fn close(&mut self) {
self.chan.close_rx();
}
pub fn is_closed(&self) -> bool {
self.chan.rx_is_closed()
}
pub fn is_empty(&self) -> bool {
self.chan.len() == 0
}
pub fn len(&self) -> usize {
self.chan.len()
}
pub fn capacity(&self) -> usize {
self.chan.limit.sem.available()
}
pub fn max_capacity(&self) -> usize {
self.chan.limit.bound
}
pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll<Option<T>> {
unsafe { self.chan.poll_recv(cx) }
}
pub fn poll_recv_many(
&mut self,
cx: &mut Context<'_>,
buffer: &mut Vec<T>,
limit: usize,
) -> Poll<usize> {
unsafe { self.chan.poll_recv_many(cx, buffer, limit) }
}
pub fn sender_strong_count(&self) -> usize {
self.chan.strong_count()
}
pub fn sender_weak_count(&self) -> usize {
self.chan.weak_count()
}
}
impl<T> Drop for Receiver<T> {
fn drop(&mut self) {
unsafe { self.chan.drop_rx() };
}
}
impl<T> fmt::Debug for Receiver<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Receiver")
.field("closed", &self.is_closed())
.field("len", &self.len())
.field("capacity", &self.capacity())
.field("max_capacity", &self.max_capacity())
.finish()
}
}