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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
//! A generic event source wrapping an `Evented` type

use std::cell::RefCell;
use std::io;
#[cfg(unix)]
use std::os::unix::io::{AsRawFd, RawFd};
use std::rc::Rc;
use std::sync::Arc;

use mio::{
    event::{Event as MioEvent, Source as MioSource},
    Interest, Registry, Token, Waker,
};

use crate::{EventDispatcher, EventSource};

/// A generic event source wrapping an `Evented` type
///
/// It will simply forward the readiness and an acces to
/// the wrapped `Evented` type to the suer callback. See
/// the `Event` type in this module.
pub struct Generic<E: MioSource + 'static> {
    inner: Rc<RefCell<E>>,
    interest: Interest,
}

impl<E: MioSource + 'static> Generic<E> {
    /// Wrap an `Evented` type into a `Generic` event source
    ///
    /// It is initialized with no interest nor poll options,
    /// as such you should set them using the `set_interest`
    /// and `set_pollopts` methods before inserting it in the
    /// event loop.
    pub fn new(source: E) -> Generic<E> {
        Self::from_rc(Rc::new(RefCell::new(source)))
    }

    /// Wrap an `Evented` type from an `Rc` into a `Generic` event source
    ///
    /// Same as the `new` method, but you can provide a source that is alreay
    /// in a reference counted pointer, so that `Generic` won't add a new
    /// layer. This is useful if you need to share this source accross multiple
    /// modules, and `calloop` is not the first one to be initialized.
    pub fn from_rc(source: Rc<RefCell<E>>) -> Generic<E> {
        Generic {
            inner: source,
            interest: Interest::READABLE,
        }
    }

    /// Change the interest for this evented source
    ///
    /// If the source was already inserted in an event loop,
    /// it needs to be re-registered for the change to take
    /// effect.
    pub fn set_interest(&mut self, interest: Interest) {
        self.interest = interest;
    }

    /// Get a clone of the inner `Rc` wrapping your event source
    pub fn clone_inner(&self) -> Rc<RefCell<E>> {
        self.inner.clone()
    }

    /// Unwrap the `Generic` source to retrieve the underlying `Evented`.
    ///
    /// If you didn't clone the `Rc<RefCell<E>>` from the `Event<E>` you received,
    /// the returned `Rc` should be unique.
    pub fn unwrap(self) -> Rc<RefCell<E>> {
        self.inner
    }
}

impl<Fd: AsRawFd> Generic<SourceFd<Fd>> {
    /// Wrap a file descriptor based source into a `Generic` event source.
    ///
    /// This will only work with poll-compatible file descriptors, which typically
    /// not include basic files.
    #[cfg(unix)]
    pub fn from_fd_source(source: Fd) -> Generic<SourceFd<Fd>> {
        Generic::new(SourceFd(source))
    }
}

impl Generic<SourceRawFd> {
    /// Wrap a raw file descriptor into a `Generic` event source.
    ///
    /// This will only work with poll-compatible file descriptors, which typically
    /// not include basic files.
    ///
    /// This does _not_ take ownership of the file descriptor, hence you are responsible
    /// of its correct lifetime.
    #[cfg(unix)]
    pub fn from_raw_fd(fd: RawFd) -> Generic<SourceRawFd> {
        Generic::new(SourceRawFd(fd))
    }
}

/// The possible readiness flags associated with the generic event source
#[derive(Copy, Clone, Debug)]
pub struct Readiness {
    /// The source is readable
    pub readable: bool,
    /// The source is writable
    pub writable: bool,
    /// The source has an error
    ///
    /// This flag is only indicative, and may be absent even if the source
    /// actually has an error, which will be signalled at the next attempt
    /// to read or write it, depending on the error.
    pub error: bool,
}

impl Readiness {
    fn empty() -> Readiness {
        Readiness {
            readable: false,
            writable: false,
            error: false,
        }
    }
}

/// An event generated by the `Generic` source
pub struct Event<E: MioSource + 'static> {
    /// An access to the source that generated this event
    pub source: Rc<RefCell<E>>,
    /// The associated rediness
    pub readiness: Readiness,
}

/// An owning wrapper implementing Evented for any file descriptor based type in Unix
#[cfg(unix)]
pub struct SourceFd<F: AsRawFd>(pub F);

impl<F: AsRawFd> MioSource for SourceFd<F> {
    fn register(
        &mut self,
        registry: &Registry,
        token: Token,
        interest: Interest,
    ) -> io::Result<()> {
        mio::unix::SourceFd(&self.0.as_raw_fd()).register(registry, token, interest)
    }

    fn reregister(
        &mut self,
        registry: &Registry,
        token: Token,
        interest: Interest,
    ) -> io::Result<()> {
        mio::unix::SourceFd(&self.0.as_raw_fd()).reregister(registry, token, interest)
    }

    fn deregister(&mut self, registry: &Registry) -> io::Result<()> {
        mio::unix::SourceFd(&self.0.as_raw_fd()).deregister(registry)
    }
}

/// A wrapper implementing Evented for any raw file descriptor.
///
/// It does _not_ take ownership of the file descriptor, you are
/// responsible for ensuring its correct lifetime.
#[cfg(unix)]
pub struct SourceRawFd(pub RawFd);

impl MioSource for SourceRawFd {
    fn register(
        &mut self,
        registry: &Registry,
        token: Token,
        interest: Interest,
    ) -> io::Result<()> {
        mio::unix::SourceFd(&self.0).register(registry, token, interest)
    }

    fn reregister(
        &mut self,
        registry: &Registry,
        token: Token,
        interest: Interest,
    ) -> io::Result<()> {
        mio::unix::SourceFd(&self.0).reregister(registry, token, interest)
    }

    fn deregister(&mut self, registry: &Registry) -> io::Result<()> {
        mio::unix::SourceFd(&self.0).deregister(registry)
    }
}

impl<E: MioSource + 'static> MioSource for Generic<E> {
    fn register(
        &mut self,
        registry: &Registry,
        token: Token,
        interest: Interest,
    ) -> io::Result<()> {
        self.inner.borrow_mut().register(registry, token, interest)
    }

    fn reregister(
        &mut self,
        registry: &Registry,
        token: Token,
        interest: Interest,
    ) -> io::Result<()> {
        self.inner
            .borrow_mut()
            .reregister(registry, token, interest)
    }

    fn deregister(&mut self, registry: &Registry) -> io::Result<()> {
        self.inner.borrow_mut().deregister(registry)
    }
}

impl<E: MioSource + 'static> EventSource for Generic<E> {
    type Event = Event<E>;

    fn interest(&self) -> Interest {
        self.interest
    }

    fn as_mio_source(&mut self) -> Option<&mut dyn MioSource> {
        Some(self)
    }

    fn make_dispatcher<Data: 'static, F: FnMut(Event<E>, &mut Data) + 'static>(
        &mut self,
        callback: F,
        _: &Arc<Waker>,
    ) -> Rc<RefCell<dyn EventDispatcher<Data>>> {
        Rc::new(RefCell::new(Dispatcher {
            _data: ::std::marker::PhantomData,
            inner: self.inner.clone(),
            callback,
        }))
    }
}

struct Dispatcher<Data, E: MioSource + 'static, F: FnMut(Event<E>, &mut Data)> {
    _data: ::std::marker::PhantomData<fn(&mut Data)>,
    inner: Rc<RefCell<E>>,
    callback: F,
}

impl<Data, E: MioSource + 'static, F: FnMut(Event<E>, &mut Data)> EventDispatcher<Data>
    for Dispatcher<Data, E, F>
{
    fn ready(&mut self, event: Option<&MioEvent>, data: &mut Data) {
        let readiness = event
            .map(|event| Readiness {
                readable: event.is_readable(),
                writable: event.is_writable(),
                error: event.is_error(),
            })
            .unwrap_or_else(Readiness::empty);
        (self.callback)(
            Event {
                source: self.inner.clone(),
                readiness,
            },
            data,
        )
    }
}

#[cfg(test)]
mod test {
    use std::io::{self, Read, Write};

    use super::{Event, Generic};
    #[cfg(unix)]
    #[test]
    fn dispatch_unix() {
        use std::os::unix::net::UnixStream;

        let mut event_loop = crate::EventLoop::new().unwrap();

        let handle = event_loop.handle();

        let (mut tx, rx) = UnixStream::pair().unwrap();

        let mut generic = Generic::from_fd_source(rx);
        generic.set_interest(mio::Interest::READABLE);

        let mut dispached = false;

        let _source = handle
            .insert_source(generic, move |Event { source, readiness }, d| {
                assert!(readiness.readable);
                // we have not registered for writability
                assert!(!readiness.writable);
                let mut buffer = vec![0; 10];
                let ret = source.borrow_mut().0.read(&mut buffer).unwrap();
                assert_eq!(ret, 6);
                assert_eq!(&buffer[..6], &[1, 2, 3, 4, 5, 6]);

                *d = true;
            })
            .map_err(Into::<io::Error>::into)
            .unwrap();

        event_loop
            .dispatch(Some(::std::time::Duration::from_millis(0)), &mut dispached)
            .unwrap();

        assert!(!dispached);

        tx.write(&[1, 2, 3, 4, 5, 6]).unwrap();
        tx.flush().unwrap();

        event_loop
            .dispatch(Some(::std::time::Duration::from_millis(0)), &mut dispached)
            .unwrap();

        assert!(dispached);
    }

    #[test]
    fn register_deregister_unix() {
        use std::os::unix::net::UnixStream;

        let mut event_loop = crate::EventLoop::new().unwrap();

        let handle = event_loop.handle();

        let (mut tx, rx) = UnixStream::pair().unwrap();

        let mut generic = Generic::from_fd_source(rx);
        generic.set_interest(mio::Interest::READABLE);

        let mut dispached = false;

        let source = handle
            .insert_source(generic, move |Event { .. }, d| {
                *d = true;
            })
            .map_err(Into::<io::Error>::into)
            .unwrap();

        event_loop
            .dispatch(Some(::std::time::Duration::from_millis(0)), &mut dispached)
            .unwrap();

        assert!(!dispached);

        // remove the source, and then write something

        let generic = source.remove();

        tx.write(&[1, 2, 3, 4, 5, 6]).unwrap();
        tx.flush().unwrap();

        event_loop
            .dispatch(Some(::std::time::Duration::from_millis(0)), &mut dispached)
            .unwrap();

        // the source has not been dispatched, as the source is no longer here
        assert!(!dispached);

        // insert it again
        let _source = handle
            .insert_source(generic, move |Event { source, readiness }, d| {
                assert!(readiness.readable);
                // we have not registered for writability
                assert!(!readiness.writable);
                let mut buffer = vec![0; 10];
                let ret = source.borrow_mut().0.read(&mut buffer).unwrap();
                assert_eq!(ret, 6);
                assert_eq!(&buffer[..6], &[1, 2, 3, 4, 5, 6]);

                *d = true;
            })
            .map_err(Into::<io::Error>::into)
            .unwrap();

        event_loop
            .dispatch(Some(::std::time::Duration::from_millis(0)), &mut dispached)
            .unwrap();

        // the has now been properly dispatched
        assert!(dispached);
    }
}