use std::cell::UnsafeCell;
use std::fmt;
use std::future::Future;
use std::isize;
use std::marker::PhantomData;
use std::mem;
use std::pin::Pin;
use std::process;
use std::ptr;
use std::sync::atomic::{self, AtomicUsize, Ordering};
use std::sync::Arc;
use std::task::{Context, Poll};
use crossbeam_utils::Backoff;
use crate::stream::Stream;
use crate::sync::WakerSet;
#[cfg(feature = "unstable")]
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
pub fn channel<T>(cap: usize) -> (Sender<T>, Receiver<T>) {
let channel = Arc::new(Channel::with_capacity(cap));
let s = Sender {
channel: channel.clone(),
};
let r = Receiver {
channel,
opt_key: None,
};
(s, r)
}
#[cfg(feature = "unstable")]
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
pub struct Sender<T> {
channel: Arc<Channel<T>>,
}
impl<T> Sender<T> {
pub async fn send(&self, msg: T) {
struct SendFuture<'a, T> {
channel: &'a Channel<T>,
msg: Option<T>,
opt_key: Option<usize>,
}
impl<T> Unpin for SendFuture<'_, T> {}
impl<T> Future for SendFuture<'_, T> {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
loop {
let msg = self.msg.take().unwrap();
if let Some(key) = self.opt_key.take() {
self.channel.send_wakers.remove(key);
}
match self.channel.try_send(msg) {
Ok(()) => return Poll::Ready(()),
Err(TrySendError::Disconnected(msg)) => {
self.msg = Some(msg);
return Poll::Pending;
}
Err(TrySendError::Full(msg)) => {
self.msg = Some(msg);
self.opt_key = Some(self.channel.send_wakers.insert(cx));
if self.channel.is_full() && !self.channel.is_disconnected() {
return Poll::Pending;
}
}
}
}
}
}
impl<T> Drop for SendFuture<'_, T> {
fn drop(&mut self) {
if let Some(key) = self.opt_key {
self.channel.send_wakers.cancel(key);
}
}
}
SendFuture {
channel: &self.channel,
msg: Some(msg),
opt_key: None,
}
.await
}
pub fn capacity(&self) -> usize {
self.channel.cap
}
pub fn is_empty(&self) -> bool {
self.channel.is_empty()
}
pub fn is_full(&self) -> bool {
self.channel.is_full()
}
pub fn len(&self) -> usize {
self.channel.len()
}
}
impl<T> Drop for Sender<T> {
fn drop(&mut self) {
if self.channel.sender_count.fetch_sub(1, Ordering::AcqRel) == 1 {
self.channel.disconnect();
}
}
}
impl<T> Clone for Sender<T> {
fn clone(&self) -> Sender<T> {
let count = self.channel.sender_count.fetch_add(1, Ordering::Relaxed);
if count > isize::MAX as usize {
process::abort();
}
Sender {
channel: self.channel.clone(),
}
}
}
impl<T> fmt::Debug for Sender<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad("Sender { .. }")
}
}
#[cfg(feature = "unstable")]
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
pub struct Receiver<T> {
channel: Arc<Channel<T>>,
opt_key: Option<usize>,
}
impl<T> Receiver<T> {
pub async fn recv(&self) -> Option<T> {
struct RecvFuture<'a, T> {
channel: &'a Channel<T>,
opt_key: Option<usize>,
}
impl<T> Future for RecvFuture<'_, T> {
type Output = Option<T>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
poll_recv(
&self.channel,
&self.channel.recv_wakers,
&mut self.opt_key,
cx,
)
}
}
impl<T> Drop for RecvFuture<'_, T> {
fn drop(&mut self) {
if let Some(key) = self.opt_key {
self.channel.recv_wakers.cancel(key);
}
}
}
RecvFuture {
channel: &self.channel,
opt_key: None,
}
.await
}
pub fn capacity(&self) -> usize {
self.channel.cap
}
pub fn is_empty(&self) -> bool {
self.channel.is_empty()
}
pub fn is_full(&self) -> bool {
self.channel.is_full()
}
pub fn len(&self) -> usize {
self.channel.len()
}
}
impl<T> Drop for Receiver<T> {
fn drop(&mut self) {
if let Some(key) = self.opt_key {
self.channel.stream_wakers.cancel(key);
}
if self.channel.receiver_count.fetch_sub(1, Ordering::AcqRel) == 1 {
self.channel.disconnect();
}
}
}
impl<T> Clone for Receiver<T> {
fn clone(&self) -> Receiver<T> {
let count = self.channel.receiver_count.fetch_add(1, Ordering::Relaxed);
if count > isize::MAX as usize {
process::abort();
}
Receiver {
channel: self.channel.clone(),
opt_key: None,
}
}
}
impl<T> Stream for Receiver<T> {
type Item = T;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = &mut *self;
poll_recv(
&this.channel,
&this.channel.stream_wakers,
&mut this.opt_key,
cx,
)
}
}
impl<T> fmt::Debug for Receiver<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad("Receiver { .. }")
}
}
fn poll_recv<T>(
channel: &Channel<T>,
wakers: &WakerSet,
opt_key: &mut Option<usize>,
cx: &mut Context<'_>,
) -> Poll<Option<T>> {
loop {
if let Some(key) = opt_key.take() {
wakers.remove(key);
}
match channel.try_recv() {
Ok(msg) => return Poll::Ready(Some(msg)),
Err(TryRecvError::Disconnected) => return Poll::Ready(None),
Err(TryRecvError::Empty) => {
*opt_key = Some(wakers.insert(cx));
if channel.is_empty() && !channel.is_disconnected() {
return Poll::Pending;
}
}
}
}
}
struct Slot<T> {
stamp: AtomicUsize,
msg: UnsafeCell<T>,
}
struct Channel<T> {
head: AtomicUsize,
tail: AtomicUsize,
buffer: *mut Slot<T>,
cap: usize,
one_lap: usize,
mark_bit: usize,
send_wakers: WakerSet,
recv_wakers: WakerSet,
stream_wakers: WakerSet,
sender_count: AtomicUsize,
receiver_count: AtomicUsize,
_marker: PhantomData<T>,
}
unsafe impl<T: Send> Send for Channel<T> {}
unsafe impl<T: Send> Sync for Channel<T> {}
impl<T> Unpin for Channel<T> {}
impl<T> Channel<T> {
fn with_capacity(cap: usize) -> Self {
assert!(cap > 0, "capacity must be positive");
let mark_bit = (cap + 1).next_power_of_two();
let one_lap = mark_bit * 2;
let head = 0;
let tail = 0;
let buffer = {
let mut v = Vec::<Slot<T>>::with_capacity(cap);
let ptr = v.as_mut_ptr();
mem::forget(v);
ptr
};
for i in 0..cap {
unsafe {
let slot = buffer.add(i);
ptr::write(&mut (*slot).stamp, AtomicUsize::new(i));
}
}
Channel {
buffer,
cap,
one_lap,
mark_bit,
head: AtomicUsize::new(head),
tail: AtomicUsize::new(tail),
send_wakers: WakerSet::new(),
recv_wakers: WakerSet::new(),
stream_wakers: WakerSet::new(),
sender_count: AtomicUsize::new(1),
receiver_count: AtomicUsize::new(1),
_marker: PhantomData,
}
}
fn try_send(&self, msg: T) -> Result<(), TrySendError<T>> {
let backoff = Backoff::new();
let mut tail = self.tail.load(Ordering::Relaxed);
loop {
let mark_bit = tail & self.mark_bit;
tail ^= mark_bit;
let index = tail & (self.mark_bit - 1);
let lap = tail & !(self.one_lap - 1);
let slot = unsafe { &*self.buffer.add(index) };
let stamp = slot.stamp.load(Ordering::Acquire);
if tail == stamp {
let new_tail = if index + 1 < self.cap {
tail + 1
} else {
lap.wrapping_add(self.one_lap)
};
match self.tail.compare_exchange_weak(
tail | mark_bit,
new_tail | mark_bit,
Ordering::SeqCst,
Ordering::Relaxed,
) {
Ok(_) => {
unsafe { slot.msg.get().write(msg) };
let stamp = tail + 1;
slot.stamp.store(stamp, Ordering::Release);
self.recv_wakers.notify_one();
self.stream_wakers.notify_all();
return Ok(());
}
Err(t) => {
tail = t;
backoff.spin();
}
}
} else if stamp.wrapping_add(self.one_lap) == tail + 1 {
atomic::fence(Ordering::SeqCst);
let head = self.head.load(Ordering::Relaxed);
if head.wrapping_add(self.one_lap) == tail {
if mark_bit != 0 {
return Err(TrySendError::Disconnected(msg));
} else {
return Err(TrySendError::Full(msg));
}
}
backoff.spin();
tail = self.tail.load(Ordering::Relaxed);
} else {
backoff.snooze();
tail = self.tail.load(Ordering::Relaxed);
}
}
}
fn try_recv(&self) -> Result<T, TryRecvError> {
let backoff = Backoff::new();
let mut head = self.head.load(Ordering::Relaxed);
loop {
let index = head & (self.mark_bit - 1);
let lap = head & !(self.one_lap - 1);
let slot = unsafe { &*self.buffer.add(index) };
let stamp = slot.stamp.load(Ordering::Acquire);
if head + 1 == stamp {
let new = if index + 1 < self.cap {
head + 1
} else {
lap.wrapping_add(self.one_lap)
};
match self.head.compare_exchange_weak(
head,
new,
Ordering::SeqCst,
Ordering::Relaxed,
) {
Ok(_) => {
let msg = unsafe { slot.msg.get().read() };
let stamp = head.wrapping_add(self.one_lap);
slot.stamp.store(stamp, Ordering::Release);
self.send_wakers.notify_one();
return Ok(msg);
}
Err(h) => {
head = h;
backoff.spin();
}
}
} else if stamp == head {
atomic::fence(Ordering::SeqCst);
let tail = self.tail.load(Ordering::Relaxed);
if (tail & !self.mark_bit) == head {
if tail & self.mark_bit != 0 {
return Err(TryRecvError::Disconnected);
} else {
return Err(TryRecvError::Empty);
}
}
backoff.spin();
head = self.head.load(Ordering::Relaxed);
} else {
backoff.snooze();
head = self.head.load(Ordering::Relaxed);
}
}
}
fn len(&self) -> usize {
loop {
let tail = self.tail.load(Ordering::SeqCst);
let head = self.head.load(Ordering::SeqCst);
if self.tail.load(Ordering::SeqCst) == tail {
let hix = head & (self.mark_bit - 1);
let tix = tail & (self.mark_bit - 1);
return if hix < tix {
tix - hix
} else if hix > tix {
self.cap - hix + tix
} else if (tail & !self.mark_bit) == head {
0
} else {
self.cap
};
}
}
}
pub fn is_disconnected(&self) -> bool {
self.tail.load(Ordering::SeqCst) & self.mark_bit != 0
}
fn is_empty(&self) -> bool {
let head = self.head.load(Ordering::SeqCst);
let tail = self.tail.load(Ordering::SeqCst);
(tail & !self.mark_bit) == head
}
fn is_full(&self) -> bool {
let tail = self.tail.load(Ordering::SeqCst);
let head = self.head.load(Ordering::SeqCst);
head.wrapping_add(self.one_lap) == tail & !self.mark_bit
}
fn disconnect(&self) {
let tail = self.tail.fetch_or(self.mark_bit, Ordering::SeqCst);
if tail & self.mark_bit == 0 {
self.send_wakers.notify_all();
self.recv_wakers.notify_all();
self.stream_wakers.notify_all();
}
}
}
impl<T> Drop for Channel<T> {
fn drop(&mut self) {
let hix = self.head.load(Ordering::Relaxed) & (self.mark_bit - 1);
for i in 0..self.len() {
let index = if hix + i < self.cap {
hix + i
} else {
hix + i - self.cap
};
unsafe {
self.buffer.add(index).drop_in_place();
}
}
unsafe {
Vec::from_raw_parts(self.buffer, 0, self.cap);
}
}
}
enum TrySendError<T> {
Full(T),
Disconnected(T),
}
enum TryRecvError {
Empty,
Disconnected,
}