calloop/sources/channel.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
//! An MPSC channel whose receiving end is an event source
//!
//! Create a channel using [`channel()`](channel), which returns a
//! [`Sender`] that can be cloned and sent accross threads if `T: Send`,
//! and a [`Channel`] that can be inserted into an [`EventLoop`](crate::EventLoop).
//! It will generate one event per message.
//!
//! A synchronous version of the channel is provided by [`sync_channel`], in which
//! the [`SyncSender`] will block when the channel is full.
use std::sync::mpsc;
use crate::{EventSource, Poll, PostAction, Readiness, Token, TokenFactory};
use super::ping::{make_ping, Ping, PingError, PingSource};
/// The events generated by the channel event source
#[derive(Debug)]
pub enum Event<T> {
/// A message was received and is bundled here
Msg(T),
/// The channel was closed
///
/// This means all the `Sender`s associated with this channel
/// have been dropped, no more messages will ever be received.
Closed,
}
/// The sender end of a channel
///
/// It can be cloned and sent accross threads (if `T` is).
#[derive(Debug)]
pub struct Sender<T> {
sender: mpsc::Sender<T>,
ping: Ping,
}
impl<T> Clone for Sender<T> {
#[cfg_attr(feature = "nightly_coverage", coverage(off))]
fn clone(&self) -> Sender<T> {
Sender {
sender: self.sender.clone(),
ping: self.ping.clone(),
}
}
}
impl<T> Sender<T> {
/// Send a message to the channel
///
/// This will wake the event loop and deliver an `Event::Msg` to
/// it containing the provided value.
pub fn send(&self, t: T) -> Result<(), mpsc::SendError<T>> {
self.sender.send(t).map(|()| self.ping.ping())
}
}
impl<T> Drop for Sender<T> {
fn drop(&mut self) {
// ping on drop, to notify about channel closure
self.ping.ping();
}
}
/// The sender end of a synchronous channel
///
/// It can be cloned and sent accross threads (if `T` is).
#[derive(Debug)]
pub struct SyncSender<T> {
sender: mpsc::SyncSender<T>,
ping: Ping,
}
impl<T> Clone for SyncSender<T> {
#[cfg_attr(feature = "nightly_coverage", coverage(off))]
fn clone(&self) -> SyncSender<T> {
SyncSender {
sender: self.sender.clone(),
ping: self.ping.clone(),
}
}
}
impl<T> SyncSender<T> {
/// Send a message to the synchronous channel
///
/// This will wake the event loop and deliver an `Event::Msg` to
/// it containing the provided value. If the channel is full, this
/// function will block until the event loop empties it and it can
/// deliver the message.
///
/// Due to the blocking behavior, this method should not be used on the
/// same thread as the one running the event loop, as it could cause deadlocks.
pub fn send(&self, t: T) -> Result<(), mpsc::SendError<T>> {
let ret = self.try_send(t);
match ret {
Ok(()) => Ok(()),
Err(mpsc::TrySendError::Full(t)) => self.sender.send(t).map(|()| self.ping.ping()),
Err(mpsc::TrySendError::Disconnected(t)) => Err(mpsc::SendError(t)),
}
}
/// Send a message to the synchronous channel
///
/// This will wake the event loop and deliver an `Event::Msg` to
/// it containing the provided value. If the channel is full, this
/// function will return an error, but the event loop will still be
/// signaled for readiness.
pub fn try_send(&self, t: T) -> Result<(), mpsc::TrySendError<T>> {
let ret = self.sender.try_send(t);
if let Ok(()) | Err(mpsc::TrySendError::Full(_)) = ret {
self.ping.ping();
}
ret
}
}
/// The receiving end of the channel
///
/// This is the event source to be inserted into your `EventLoop`.
#[derive(Debug)]
pub struct Channel<T> {
receiver: mpsc::Receiver<T>,
source: PingSource,
}
// This impl is safe because the Channel is only able to move around threads
// when it is not inserted into an event loop. (Otherwise it is stuck into
// a Source<_> and the internals of calloop, which are not Send).
// At this point, the Arc<Receiver> has a count of 1, and it is obviously
// safe to Send between threads.
unsafe impl<T: Send> Send for Channel<T> {}
impl<T> Channel<T> {
/// Proxy for [`mpsc::Receiver::recv`] to manually poll events.
///
/// *Note*: Normally you would want to use the `Channel` by inserting
/// it into an event loop instead. Use this for example to immediately
/// dispatch pending events after creation.
pub fn recv(&self) -> Result<T, mpsc::RecvError> {
self.receiver.recv()
}
/// Proxy for [`mpsc::Receiver::try_recv`] to manually poll events.
///
/// *Note*: Normally you would want to use the `Channel` by inserting
/// it into an event loop instead. Use this for example to immediately
/// dispatch pending events after creation.
pub fn try_recv(&self) -> Result<T, mpsc::TryRecvError> {
self.receiver.try_recv()
}
}
/// Create a new asynchronous channel
pub fn channel<T>() -> (Sender<T>, Channel<T>) {
let (sender, receiver) = mpsc::channel();
let (ping, source) = make_ping().expect("Failed to create a Ping.");
(Sender { sender, ping }, Channel { receiver, source })
}
/// Create a new synchronous, bounded channel
pub fn sync_channel<T>(bound: usize) -> (SyncSender<T>, Channel<T>) {
let (sender, receiver) = mpsc::sync_channel(bound);
let (ping, source) = make_ping().expect("Failed to create a Ping.");
(SyncSender { sender, ping }, Channel { receiver, source })
}
impl<T> EventSource for Channel<T> {
type Event = Event<T>;
type Metadata = ();
type Ret = ();
type Error = ChannelError;
fn process_events<C>(
&mut self,
readiness: Readiness,
token: Token,
mut callback: C,
) -> Result<PostAction, Self::Error>
where
C: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
{
let receiver = &self.receiver;
self.source
.process_events(readiness, token, |(), &mut ()| loop {
match receiver.try_recv() {
Ok(val) => callback(Event::Msg(val), &mut ()),
Err(mpsc::TryRecvError::Empty) => break,
Err(mpsc::TryRecvError::Disconnected) => {
callback(Event::Closed, &mut ());
break;
}
}
})
.map_err(ChannelError)
}
fn register(&mut self, poll: &mut Poll, token_factory: &mut TokenFactory) -> crate::Result<()> {
self.source.register(poll, token_factory)
}
fn reregister(
&mut self,
poll: &mut Poll,
token_factory: &mut TokenFactory,
) -> crate::Result<()> {
self.source.reregister(poll, token_factory)
}
fn unregister(&mut self, poll: &mut Poll) -> crate::Result<()> {
self.source.unregister(poll)
}
}
/// An error arising from processing events for a channel.
#[derive(thiserror::Error, Debug)]
#[error(transparent)]
pub struct ChannelError(PingError);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn basic_channel() {
let mut event_loop = crate::EventLoop::try_new().unwrap();
let handle = event_loop.handle();
let (tx, rx) = channel::<()>();
// (got_msg, got_closed)
let mut got = (false, false);
let _channel_token = handle
.insert_source(rx, move |evt, &mut (), got: &mut (bool, bool)| match evt {
Event::Msg(()) => {
got.0 = true;
}
Event::Closed => {
got.1 = true;
}
})
.unwrap();
// nothing is sent, nothing is received
event_loop
.dispatch(Some(::std::time::Duration::ZERO), &mut got)
.unwrap();
assert_eq!(got, (false, false));
// a message is send
tx.send(()).unwrap();
event_loop
.dispatch(Some(::std::time::Duration::ZERO), &mut got)
.unwrap();
assert_eq!(got, (true, false));
// the sender is dropped
::std::mem::drop(tx);
event_loop
.dispatch(Some(::std::time::Duration::ZERO), &mut got)
.unwrap();
assert_eq!(got, (true, true));
}
#[test]
fn basic_sync_channel() {
let mut event_loop = crate::EventLoop::try_new().unwrap();
let handle = event_loop.handle();
let (tx, rx) = sync_channel::<()>(2);
let mut received = (0, false);
let _channel_token = handle
.insert_source(
rx,
move |evt, &mut (), received: &mut (u32, bool)| match evt {
Event::Msg(()) => {
received.0 += 1;
}
Event::Closed => {
received.1 = true;
}
},
)
.unwrap();
// nothing is sent, nothing is received
event_loop
.dispatch(Some(::std::time::Duration::ZERO), &mut received)
.unwrap();
assert_eq!(received.0, 0);
assert!(!received.1);
// fill the channel
tx.send(()).unwrap();
tx.send(()).unwrap();
assert!(tx.try_send(()).is_err());
// empty it
event_loop
.dispatch(Some(::std::time::Duration::ZERO), &mut received)
.unwrap();
assert_eq!(received.0, 2);
assert!(!received.1);
// send a final message and drop the sender
tx.send(()).unwrap();
std::mem::drop(tx);
// final read of the channel
event_loop
.dispatch(Some(::std::time::Duration::ZERO), &mut received)
.unwrap();
assert_eq!(received.0, 3);
assert!(received.1);
}
}