|
| 1 | +use futures::{future, ready, Stream}; |
| 2 | +use std::sync::{Arc, Weak}; |
| 3 | +use std::task::{Context, Poll}; |
| 4 | +use std::{fmt, future::Future, mem, pin::Pin}; |
| 5 | +use tokio::sync::{mpsc, OwnedSemaphorePermit as Permit, Semaphore}; |
| 6 | + |
| 7 | +use self::error::{SendError, TrySendError}; |
| 8 | +pub use tokio::sync::mpsc::error; |
| 9 | + |
| 10 | +/// Returns a new pollable, bounded MPSC channel. |
| 11 | +/// |
| 12 | +/// Unlike `tokio::sync`'s `MPSC` channel, this channel exposes a `poll_ready` |
| 13 | +/// function, at the cost of an allocation when driving it to readiness. |
| 14 | +pub fn channel<T>(buffer: usize) -> (Sender<T>, Receiver<T>) { |
| 15 | + assert!(buffer > 0, "mpsc bounded channel requires buffer > 0"); |
| 16 | + let semaphore = Arc::new(Semaphore::new(buffer)); |
| 17 | + let (tx, rx) = mpsc::unbounded_channel(); |
| 18 | + let rx = Receiver { |
| 19 | + rx, |
| 20 | + semaphore: Arc::downgrade(&semaphore), |
| 21 | + buffer, |
| 22 | + }; |
| 23 | + let tx = Sender { |
| 24 | + tx, |
| 25 | + semaphore, |
| 26 | + state: State::Empty, |
| 27 | + }; |
| 28 | + (tx, rx) |
| 29 | +} |
| 30 | + |
| 31 | +/// A bounded, pollable MPSC sender. |
| 32 | +/// |
| 33 | +/// This is similar to Tokio's bounded MPSC channel's `Sender` type, except that |
| 34 | +/// it exposes a `poll_ready` function, at the cost of an allocation when |
| 35 | +/// driving it to readiness. |
| 36 | +pub struct Sender<T> { |
| 37 | + tx: mpsc::UnboundedSender<(T, Permit)>, |
| 38 | + semaphore: Arc<Semaphore>, |
| 39 | + state: State, |
| 40 | +} |
| 41 | + |
| 42 | +/// A bounded MPSC receiver. |
| 43 | +/// |
| 44 | +/// This is similar to Tokio's bounded MPSC channel's `Receiver` type. |
| 45 | +pub struct Receiver<T> { |
| 46 | + rx: mpsc::UnboundedReceiver<(T, Permit)>, |
| 47 | + semaphore: Weak<Semaphore>, |
| 48 | + buffer: usize, |
| 49 | +} |
| 50 | + |
| 51 | +enum State { |
| 52 | + Waiting(Pin<Box<dyn Future<Output = Permit> + Send + Sync>>), |
| 53 | + Acquired(Permit), |
| 54 | + Empty, |
| 55 | +} |
| 56 | + |
| 57 | +impl<T> Sender<T> { |
| 58 | + pub fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), SendError<()>>> { |
| 59 | + loop { |
| 60 | + self.state = match self.state { |
| 61 | + State::Empty => State::Waiting(Box::pin(self.semaphore.clone().acquire_owned())), |
| 62 | + State::Waiting(ref mut f) => State::Acquired(ready!(Pin::new(f).poll(cx))), |
| 63 | + State::Acquired(_) if self.tx.is_closed() => { |
| 64 | + return Poll::Ready(Err(SendError(()))) |
| 65 | + } |
| 66 | + State::Acquired(_) => return Poll::Ready(Ok(())), |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + pub async fn ready(&mut self) -> Result<(), SendError<()>> { |
| 72 | + future::poll_fn(|cx| self.poll_ready(cx)).await |
| 73 | + } |
| 74 | + |
| 75 | + pub fn try_send(&mut self, value: T) -> Result<(), TrySendError<T>> { |
| 76 | + if self.tx.is_closed() { |
| 77 | + return Err(TrySendError::Closed(value)); |
| 78 | + } |
| 79 | + self.state = match mem::replace(&mut self.state, State::Empty) { |
| 80 | + // Have we previously acquired a permit? |
| 81 | + State::Acquired(permit) => { |
| 82 | + self.send2(value, permit); |
| 83 | + return Ok(()); |
| 84 | + } |
| 85 | + // Okay, can we acquire a permit now? |
| 86 | + State::Empty => { |
| 87 | + if let Ok(permit) = self.semaphore.clone().try_acquire_owned() { |
| 88 | + self.send2(value, permit); |
| 89 | + return Ok(()); |
| 90 | + } |
| 91 | + State::Empty |
| 92 | + } |
| 93 | + state => state, |
| 94 | + }; |
| 95 | + Err(TrySendError::Full(value)) |
| 96 | + } |
| 97 | + |
| 98 | + pub async fn send(&mut self, value: T) -> Result<(), SendError<T>> { |
| 99 | + if let Err(_) = self.ready().await { |
| 100 | + return Err(SendError(value)); |
| 101 | + } |
| 102 | + match mem::replace(&mut self.state, State::Empty) { |
| 103 | + State::Acquired(permit) => { |
| 104 | + self.send2(value, permit); |
| 105 | + Ok(()) |
| 106 | + } |
| 107 | + state => panic!("unexpected state after poll_ready: {:?}", state), |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + fn send2(&mut self, value: T, permit: Permit) { |
| 112 | + self.tx.send((value, permit)).ok().expect("was not closed"); |
| 113 | + } |
| 114 | +} |
| 115 | + |
| 116 | +impl<T> Clone for Sender<T> { |
| 117 | + fn clone(&self) -> Self { |
| 118 | + Self { |
| 119 | + tx: self.tx.clone(), |
| 120 | + semaphore: self.semaphore.clone(), |
| 121 | + state: State::Empty, |
| 122 | + } |
| 123 | + } |
| 124 | +} |
| 125 | + |
| 126 | +impl<T> fmt::Debug for Sender<T> { |
| 127 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 128 | + f.debug_struct("Sender") |
| 129 | + .field("message_type", &std::any::type_name::<T>()) |
| 130 | + .field("state", &self.state) |
| 131 | + .field("semaphore", &self.semaphore) |
| 132 | + .finish() |
| 133 | + } |
| 134 | +} |
| 135 | + |
| 136 | +// === impl Receiver === |
| 137 | + |
| 138 | +impl<T> Receiver<T> { |
| 139 | + pub async fn recv(&mut self) -> Option<T> { |
| 140 | + self.rx.recv().await.map(|(t, _)| t) |
| 141 | + } |
| 142 | + |
| 143 | + pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll<Option<T>> { |
| 144 | + let res = ready!(Pin::new(&mut self.rx).poll_next(cx)); |
| 145 | + Poll::Ready(res.map(|(t, _)| t)) |
| 146 | + } |
| 147 | +} |
| 148 | + |
| 149 | +impl<T> Stream for Receiver<T> { |
| 150 | + type Item = T; |
| 151 | + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { |
| 152 | + let res = ready!(Pin::new(&mut self.as_mut().rx).poll_next(cx)); |
| 153 | + Poll::Ready(res.map(|(t, _)| t)) |
| 154 | + } |
| 155 | +} |
| 156 | + |
| 157 | +impl<T> Drop for Receiver<T> { |
| 158 | + fn drop(&mut self) { |
| 159 | + if let Some(semaphore) = self.semaphore.upgrade() { |
| 160 | + // Close the buffer by releasing any senders waiting on channel capacity. |
| 161 | + // If more than `usize::MAX >> 3` permits are added to the semaphore, it |
| 162 | + // will panic. |
| 163 | + const MAX: usize = std::usize::MAX >> 4; |
| 164 | + semaphore.add_permits(MAX - self.buffer - semaphore.available_permits()); |
| 165 | + } |
| 166 | + } |
| 167 | +} |
| 168 | + |
| 169 | +impl<T> fmt::Debug for Receiver<T> { |
| 170 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 171 | + f.debug_struct("Receiver") |
| 172 | + .field("message_type", &std::any::type_name::<T>()) |
| 173 | + .field("semaphore", &self.semaphore) |
| 174 | + .finish() |
| 175 | + } |
| 176 | +} |
| 177 | + |
| 178 | +// === impl State === |
| 179 | + |
| 180 | +impl fmt::Debug for State { |
| 181 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 182 | + fmt::Display::fmt( |
| 183 | + match self { |
| 184 | + State::Acquired(_) => "State::Acquired(..)", |
| 185 | + State::Waiting(_) => "State::Waiting(..)", |
| 186 | + State::Empty => "State::Empty", |
| 187 | + }, |
| 188 | + f, |
| 189 | + ) |
| 190 | + } |
| 191 | +} |
0 commit comments