| 1 |
//! Adapt a [`Stream`] into an event source |
| 2 |
//! |
| 3 |
//! Only available with the `stream` cargo feature of `calloop`. |
| 4 |
//! |
| 5 |
//! The stream will be polled by the event loop, allowing the event source's |
| 6 |
//! callback to handle each event from the stream. This allows streams that |
| 7 |
//! are woken by events in a different thread to be naturally integrated into |
| 8 |
//! a `calloop` event loop. |
| 9 |
|
| 10 |
use futures_core::Stream; |
| 11 |
use std::{ |
| 12 |
fmt, |
| 13 |
pin::pin, |
| 14 |
sync::Arc, |
| 15 |
task::{Context, Wake, Waker}, |
| 16 |
}; |
| 17 |
|
| 18 |
use crate::{ |
| 19 |
ping::{make_ping, Ping, PingError, PingSource}, |
| 20 |
EventSource, Poll, PostAction, Readiness, Token, TokenFactory, |
| 21 |
}; |
| 22 |
|
| 23 |
struct PingWaker(Ping); |
| 24 |
|
| 25 |
impl Wake for PingWaker { |
| 26 |
fn wake(self: Arc<Self>) { |
| 27 |
self.0.ping(); |
| 28 |
} |
| 29 |
|
| 30 |
#[cfg_attr(feature = "nightly_coverage", coverage(off))] |
| 31 |
fn wake_by_ref(self: &Arc<Self>) { |
| 32 |
self.0.ping(); |
| 33 |
} |
| 34 |
} |
| 35 |
|
| 36 |
/// [`Stream`]-based event source. |
| 37 |
#[derive(Debug)] |
| 38 |
pub struct StreamSource<S: Stream + Unpin> { |
| 39 |
stream: S, |
| 40 |
source: PingSource, |
| 41 |
waker: Waker, |
| 42 |
} |
| 43 |
|
| 44 |
impl<S: Stream + Unpin> StreamSource<S> { |
| 45 |
/// Create event source for a [`Stream`]. |
| 46 |
pub fn new(stream: S) -> crate::Result<Self> { |
| 47 |
let (ping, source) = make_ping()?; |
| 48 |
|
| 49 |
// Signal the ping source so the stream will be polled initially, |
| 50 |
// and the waker registered. |
| 51 |
ping.ping(); |
| 52 |
|
| 53 |
let waker = Waker::from(Arc::new(PingWaker(ping))); |
| 54 |
|
| 55 |
Ok(Self { |
| 56 |
stream: stream, |
| 57 |
source, |
| 58 |
waker, |
| 59 |
}) |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
impl<S: Stream + Unpin> EventSource for StreamSource<S> { |
| 64 |
type Event = Option<S::Item>; |
| 65 |
type Metadata = (); |
| 66 |
type Ret = (); |
| 67 |
type Error = StreamError; |
| 68 |
|
| 69 |
fn process_events<F>( |
| 70 |
&mut self, |
| 71 |
readiness: Readiness, |
| 72 |
token: Token, |
| 73 |
mut callback: F, |
| 74 |
) -> Result<PostAction, Self::Error> |
| 75 |
where |
| 76 |
F: FnMut(Option<S::Item>, &mut ()), |
| 77 |
{ |
| 78 |
let mut context = Context::from_waker(&self.waker); |
| 79 |
let mut stream = pin!(&mut self.stream); |
| 80 |
let mut end_of_stream = false; |
| 81 |
let action = self |
| 82 |
.source |
| 83 |
.process_events(readiness, token, |(), &mut ()| { |
| 84 |
while let std::task::Poll::Ready(evt) = stream.as_mut().poll_next(&mut context) { |
| 85 |
if let Some(evt) = evt { |
| 86 |
callback(Some(evt), &mut ()); |
| 87 |
} else { |
| 88 |
callback(None, &mut ()); |
| 89 |
end_of_stream = true; |
| 90 |
break; |
| 91 |
} |
| 92 |
} |
| 93 |
})?; |
| 94 |
if end_of_stream { |
| 95 |
Ok(PostAction::Remove) |
| 96 |
} else { |
| 97 |
Ok(action) |
| 98 |
} |
| 99 |
} |
| 100 |
|
| 101 |
fn register(&mut self, poll: &mut Poll, token_factory: &mut TokenFactory) -> crate::Result<()> { |
| 102 |
self.source.register(poll, token_factory)?; |
| 103 |
Ok(()) |
| 104 |
} |
| 105 |
|
| 106 |
fn reregister( |
| 107 |
&mut self, |
| 108 |
poll: &mut Poll, |
| 109 |
token_factory: &mut TokenFactory, |
| 110 |
) -> crate::Result<()> { |
| 111 |
self.source.reregister(poll, token_factory)?; |
| 112 |
Ok(()) |
| 113 |
} |
| 114 |
|
| 115 |
fn unregister(&mut self, poll: &mut Poll) -> crate::Result<()> { |
| 116 |
self.source.unregister(poll)?; |
| 117 |
Ok(()) |
| 118 |
} |
| 119 |
} |
| 120 |
|
| 121 |
/// An error arising from processing events for a stream. |
| 122 |
#[derive(Debug)] |
| 123 |
pub struct StreamError(PingError); |
| 124 |
|
| 125 |
impl fmt::Display for StreamError { |
| 126 |
#[cfg_attr(feature = "nightly_coverage", coverage(off))] |
| 127 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 128 |
fmt::Display::fmt(&self.0, f) |
| 129 |
} |
| 130 |
} |
| 131 |
|
| 132 |
impl std::error::Error for StreamError { |
| 133 |
#[cfg_attr(feature = "nightly_coverage", coverage(off))] |
| 134 |
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { |
| 135 |
Some(&self.0) |
| 136 |
} |
| 137 |
} |
| 138 |
|
| 139 |
impl From<PingError> for StreamError { |
| 140 |
#[cfg_attr(feature = "nightly_coverage", coverage(off))] |
| 141 |
fn from(err: PingError) -> Self { |
| 142 |
Self(err) |
| 143 |
} |
| 144 |
} |
| 145 |
|
| 146 |
#[cfg(test)] |
| 147 |
mod tests { |
| 148 |
use futures::channel::mpsc; |
| 149 |
use std::{thread, time::Duration}; |
| 150 |
|
| 151 |
use super::*; |
| 152 |
|
| 153 |
#[test] |
| 154 |
fn channel_stream() { |
| 155 |
let mut event_loop = crate::EventLoop::<usize>::try_new().unwrap(); |
| 156 |
|
| 157 |
let (mut sender, receiver) = mpsc::channel(5); |
| 158 |
|
| 159 |
let source = StreamSource::new(receiver).unwrap(); |
| 160 |
let token = event_loop |
| 161 |
.handle() |
| 162 |
.insert_source(source, |evt, (), count| { |
| 163 |
if let Some(()) = evt { |
| 164 |
*count += 1; |
| 165 |
} |
| 166 |
}) |
| 167 |
.unwrap(); |
| 168 |
|
| 169 |
thread::spawn(move || { |
| 170 |
thread::sleep(Duration::from_millis(100)); |
| 171 |
sender.try_send(()).unwrap(); |
| 172 |
thread::sleep(Duration::from_millis(100)); |
| 173 |
sender.try_send(()).unwrap(); |
| 174 |
}); |
| 175 |
|
| 176 |
let mut count = 0; |
| 177 |
event_loop.dispatch(Duration::ZERO, &mut count).unwrap(); |
| 178 |
event_loop.handle().update(&token); |
| 179 |
while count < 2 { |
| 180 |
event_loop.dispatch(Duration::ZERO, &mut count).unwrap(); |
| 181 |
} |
| 182 |
} |
| 183 |
} |