mio/
poll.rs

1#[cfg(all(
2    unix,
3    not(mio_unsupported_force_poll_poll),
4    not(any(
5        target_os = "espidf",
6        target_os = "fuchsia",
7        target_os = "haiku",
8        target_os = "hermit",
9        target_os = "hurd",
10        target_os = "nto",
11        target_os = "solaris",
12        target_os = "vita"
13    )),
14))]
15use std::os::fd::{AsRawFd, RawFd};
16#[cfg(all(debug_assertions, not(target_os = "wasi")))]
17use std::sync::atomic::{AtomicBool, Ordering};
18#[cfg(all(debug_assertions, not(target_os = "wasi")))]
19use std::sync::Arc;
20use std::time::Duration;
21use std::{fmt, io};
22
23use crate::{event, sys, Events, Interest, Token};
24
25/// Polls for readiness events on all registered values.
26///
27/// `Poll` allows a program to monitor a large number of [`event::Source`]s,
28/// waiting until one or more become "ready" for some class of operations; e.g.
29/// reading and writing. An event source is considered ready if it is possible
30/// to immediately perform a corresponding operation; e.g. [`read`] or
31/// [`write`].
32///
33/// To use `Poll`, an `event::Source` must first be registered with the `Poll`
34/// instance using the [`register`] method on its associated `Register`,
35/// supplying readiness interest. The readiness interest tells `Poll` which
36/// specific operations on the handle to monitor for readiness. A `Token` is
37/// also passed to the [`register`] function. When `Poll` returns a readiness
38/// event, it will include this token.  This associates the event with the
39/// event source that generated the event.
40///
41/// [`event::Source`]: ./event/trait.Source.html
42/// [`read`]: ./net/struct.TcpStream.html#method.read
43/// [`write`]: ./net/struct.TcpStream.html#method.write
44/// [`register`]: struct.Registry.html#method.register
45///
46/// # Examples
47///
48/// A basic example -- establishing a `TcpStream` connection.
49///
50#[cfg_attr(all(feature = "os-poll", feature = "net"), doc = "```")]
51#[cfg_attr(not(all(feature = "os-poll", feature = "net")), doc = "```ignore")]
52/// # use std::error::Error;
53/// # fn main() -> Result<(), Box<dyn Error>> {
54/// use mio::{Events, Poll, Interest, Token};
55/// use mio::net::TcpStream;
56///
57/// use std::net::{self, SocketAddr};
58///
59/// // Bind a server socket to connect to.
60/// let addr: SocketAddr = "127.0.0.1:0".parse()?;
61/// let server = net::TcpListener::bind(addr)?;
62///
63/// // Construct a new `Poll` handle as well as the `Events` we'll store into
64/// let mut poll = Poll::new()?;
65/// let mut events = Events::with_capacity(1024);
66///
67/// // Connect the stream
68/// let mut stream = TcpStream::connect(server.local_addr()?)?;
69///
70/// // Register the stream with `Poll`
71/// poll.registry().register(&mut stream, Token(0), Interest::READABLE | Interest::WRITABLE)?;
72///
73/// // Wait for the socket to become ready. This has to happens in a loop to
74/// // handle spurious wakeups.
75/// loop {
76///     poll.poll(&mut events, None)?;
77///
78///     for event in &events {
79///         if event.token() == Token(0) && event.is_writable() {
80///             // The socket connected (probably, it could still be a spurious
81///             // wakeup)
82///             return Ok(());
83///         }
84///     }
85/// }
86/// # }
87/// ```
88///
89/// # Portability
90///
91/// Using `Poll` provides a portable interface across supported platforms as
92/// long as the caller takes the following into consideration:
93///
94/// ### Spurious events
95///
96/// [`Poll::poll`] may return readiness events even if the associated
97/// event source is not actually ready. Given the same code, this may
98/// happen more on some platforms than others. It is important to never assume
99/// that, just because a readiness event was received, that the associated
100/// operation will succeed as well.
101///
102/// If operation fails with [`WouldBlock`], then the caller should not treat
103/// this as an error, but instead should wait until another readiness event is
104/// received.
105///
106/// ### Draining readiness
107///
108/// Once a readiness event is received, the corresponding operation must be
109/// performed repeatedly until it returns [`WouldBlock`]. Unless this is done,
110/// there is no guarantee that another readiness event will be delivered, even
111/// if further data is received for the event source.
112///
113/// [`WouldBlock`]: std::io::ErrorKind::WouldBlock
114///
115/// ### Readiness operations
116///
117/// The only readiness operations that are guaranteed to be present on all
118/// supported platforms are [`readable`] and [`writable`]. All other readiness
119/// operations may have false negatives and as such should be considered
120/// **hints**. This means that if a socket is registered with [`readable`]
121/// interest and either an error or close is received, a readiness event will
122/// be generated for the socket, but it **may** only include `readable`
123/// readiness. Also note that, given the potential for spurious events,
124/// receiving a readiness event with `read_closed`, `write_closed`, or `error`
125/// doesn't actually mean that a `read` on the socket will return a result
126/// matching the readiness event.
127///
128/// In other words, portable programs that explicitly check for [`read_closed`],
129/// [`write_closed`], or [`error`] readiness should be doing so as an
130/// **optimization** and always be able to handle an error or close situation
131/// when performing the actual read operation.
132///
133/// [`readable`]: ./event/struct.Event.html#method.is_readable
134/// [`writable`]: ./event/struct.Event.html#method.is_writable
135/// [`error`]: ./event/struct.Event.html#method.is_error
136/// [`read_closed`]: ./event/struct.Event.html#method.is_read_closed
137/// [`write_closed`]: ./event/struct.Event.html#method.is_write_closed
138///
139/// ### Registering handles
140///
141/// Unless otherwise noted, it should be assumed that types implementing
142/// [`event::Source`] will never become ready unless they are registered with
143/// `Poll`.
144///
145/// For example:
146///
147#[cfg_attr(all(feature = "os-poll", feature = "net"), doc = "```")]
148#[cfg_attr(not(all(feature = "os-poll", feature = "net")), doc = "```ignore")]
149/// # use std::error::Error;
150/// # use std::net;
151/// # fn main() -> Result<(), Box<dyn Error>> {
152/// use mio::{Poll, Interest, Token};
153/// use mio::net::TcpStream;
154/// use std::net::SocketAddr;
155/// use std::time::Duration;
156/// use std::thread;
157///
158/// let address: SocketAddr = "127.0.0.1:0".parse()?;
159/// let listener = net::TcpListener::bind(address)?;
160/// let mut sock = TcpStream::connect(listener.local_addr()?)?;
161///
162/// thread::sleep(Duration::from_secs(1));
163///
164/// let poll = Poll::new()?;
165///
166/// // The connect is not guaranteed to have started until it is registered at
167/// // this point
168/// poll.registry().register(&mut sock, Token(0), Interest::READABLE | Interest::WRITABLE)?;
169/// #     Ok(())
170/// # }
171/// ```
172///
173/// ### Dropping `Poll`
174///
175/// When the `Poll` instance is dropped it may cancel in-flight operations for
176/// the registered [event sources], meaning that no further events for them may
177/// be received. It also means operations on the registered event sources may no
178/// longer work. It is up to the user to keep the `Poll` instance alive while
179/// registered event sources are being used.
180///
181/// [event sources]: ./event/trait.Source.html
182///
183/// ### Accessing raw fd/socket/handle
184///
185/// Mio makes it possible for many types to be converted into a raw file
186/// descriptor (fd, Unix), socket (Windows) or handle (Windows). This makes it
187/// possible to support more operations on the type than Mio supports, for
188/// example it makes [mio-aio] possible. However accessing the raw fd is not
189/// without it's pitfalls.
190///
191/// Specifically performing I/O operations outside of Mio on these types (via
192/// the raw fd) has unspecified behaviour. It could cause no more events to be
193/// generated for the type even though it returned `WouldBlock` (in an operation
194/// directly accessing the fd). The behaviour is OS specific and Mio can only
195/// guarantee cross-platform behaviour if it can control the I/O.
196///
197/// [mio-aio]: https://github.com/asomers/mio-aio
198///
199/// *The following is **not** guaranteed, just a description of the current
200/// situation!* Mio is allowed to change the following without it being considered
201/// a breaking change, don't depend on this, it's just here to inform the user.
202/// Currently the kqueue and epoll implementation support direct I/O operations
203/// on the fd without Mio's knowledge. Windows however needs **all** I/O
204/// operations to go through Mio otherwise it is not able to update it's
205/// internal state properly and won't generate events.
206///
207/// ### Polling without registering event sources
208///
209///
210/// *The following is **not** guaranteed, just a description of the current
211/// situation!* Mio is allowed to change the following without it being
212/// considered a breaking change, don't depend on this, it's just here to inform
213/// the user. On platforms that use epoll, kqueue or IOCP (see implementation
214/// notes below) polling without previously registering [event sources] will
215/// result in sleeping forever, only a process signal will be able to wake up
216/// the thread.
217///
218/// On WASM/WASI this is different as it doesn't support process signals,
219/// furthermore the WASI specification doesn't specify a behaviour in this
220/// situation, thus it's up to the implementation what to do here. As an
221/// example, the wasmtime runtime will return `EINVAL` in this situation, but
222/// different runtimes may return different results. If you have further
223/// insights or thoughts about this situation (and/or how Mio should handle it)
224/// please add you comment to [pull request#1580].
225///
226/// [event sources]: crate::event::Source
227/// [pull request#1580]: https://github.com/tokio-rs/mio/pull/1580
228///
229/// # Implementation notes
230///
231/// `Poll` is backed by the selector provided by the operating system.
232///
233/// |      OS       |  Selector |
234/// |---------------|-----------|
235/// | Android       | [epoll]   |
236/// | DragonFly BSD | [kqueue]  |
237/// | FreeBSD       | [kqueue]  |
238/// | iOS           | [kqueue]  |
239/// | illumos       | [epoll]   |
240/// | Linux         | [epoll]   |
241/// | NetBSD        | [kqueue]  |
242/// | OpenBSD       | [kqueue]  |
243/// | Windows       | [IOCP]    |
244/// | macOS         | [kqueue]  |
245///
246/// On all supported platforms, socket operations are handled by using the
247/// system selector. Platform specific extensions (e.g. [`SourceFd`]) allow
248/// accessing other features provided by individual system selectors. For
249/// example, Linux's [`signalfd`] feature can be used by registering the FD with
250/// `Poll` via [`SourceFd`].
251///
252/// On all platforms except windows, a call to [`Poll::poll`] is mostly just a
253/// direct call to the system selector. However, [IOCP] uses a completion model
254/// instead of a readiness model. In this case, `Poll` must adapt the completion
255/// model Mio's API. While non-trivial, the bridge layer is still quite
256/// efficient. The most expensive part being calls to `read` and `write` require
257/// data to be copied into an intermediate buffer before it is passed to the
258/// kernel.
259///
260/// [epoll]: https://man7.org/linux/man-pages/man7/epoll.7.html
261/// [kqueue]: https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2
262/// [IOCP]: https://docs.microsoft.com/en-us/windows/win32/fileio/i-o-completion-ports
263/// [`signalfd`]: https://man7.org/linux/man-pages/man2/signalfd.2.html
264/// [`SourceFd`]: unix/struct.SourceFd.html
265/// [`Poll::poll`]: struct.Poll.html#method.poll
266pub struct Poll {
267    registry: Registry,
268}
269
270/// Registers I/O resources.
271pub struct Registry {
272    selector: sys::Selector,
273    /// Whether this selector currently has an associated waker.
274    #[cfg(all(debug_assertions, not(target_os = "wasi")))]
275    has_waker: Arc<AtomicBool>,
276}
277
278impl Poll {
279    cfg_os_poll! {
280        /// Return a new `Poll` handle.
281        ///
282        /// This function will make a syscall to the operating system to create
283        /// the system selector. If this syscall fails, `Poll::new` will return
284        /// with the error.
285        ///
286        /// close-on-exec flag is set on the file descriptors used by the selector to prevent
287        /// leaking it to executed processes. However, on some systems such as
288        /// old Linux systems that don't support `epoll_create1` syscall it is done
289        /// non-atomically, so a separate thread executing in parallel to this
290        /// function may accidentally leak the file descriptor if it executes a
291        /// new process before this function returns.
292        ///
293        /// See [struct] level docs for more details.
294        ///
295        /// [struct]: struct.Poll.html
296        ///
297        /// # Examples
298        ///
299        /// ```
300        /// # use std::error::Error;
301        /// # fn main() -> Result<(), Box<dyn Error>> {
302        /// use mio::{Poll, Events};
303        /// use std::time::Duration;
304        ///
305        /// let mut poll = match Poll::new() {
306        ///     Ok(poll) => poll,
307        ///     Err(e) => panic!("failed to create Poll instance; err={:?}", e),
308        /// };
309        ///
310        /// // Create a structure to receive polled events
311        /// let mut events = Events::with_capacity(1024);
312        ///
313        /// // Wait for events, but none will be received because no
314        /// // `event::Source`s have been registered with this `Poll` instance.
315        /// poll.poll(&mut events, Some(Duration::from_millis(500)))?;
316        /// assert!(events.is_empty());
317        /// #     Ok(())
318        /// # }
319        /// ```
320        pub fn new() -> io::Result<Poll> {
321            sys::Selector::new().map(|selector| Poll {
322                registry: Registry {
323                    selector,
324                    #[cfg(all(debug_assertions, not(target_os = "wasi")))]
325                    has_waker: Arc::new(AtomicBool::new(false)),
326                },
327            })
328        }
329    }
330
331    /// Create a separate `Registry` which can be used to register
332    /// `event::Source`s.
333    pub fn registry(&self) -> &Registry {
334        &self.registry
335    }
336
337    /// Wait for readiness events
338    ///
339    /// Blocks the current thread and waits for readiness events for any of the
340    /// [`event::Source`]s that have been registered with this `Poll` instance.
341    /// The function will block until either at least one readiness event has
342    /// been received or `timeout` has elapsed. A `timeout` of `None` means that
343    /// `poll` will block until a readiness event has been received.
344    ///
345    /// The supplied `events` will be cleared and newly received readiness events
346    /// will be pushed onto the end. At most `events.capacity()` events will be
347    /// returned. If there are further pending readiness events, they will be
348    /// returned on the next call to `poll`.
349    ///
350    /// A single call to `poll` may result in multiple readiness events being
351    /// returned for a single event source. For example, if a TCP socket becomes
352    /// both readable and writable, it may be possible for a single readiness
353    /// event to be returned with both [`readable`] and [`writable`] readiness
354    /// **OR** two separate events may be returned, one with [`readable`] set
355    /// and one with [`writable`] set.
356    ///
357    /// Note that the `timeout` will be rounded up to the system clock
358    /// granularity (usually 1ms), and kernel scheduling delays mean that
359    /// the blocking interval may be overrun by a small amount.
360    ///
361    /// See the [struct] level documentation for a higher level discussion of
362    /// polling.
363    ///
364    /// [`event::Source`]: ./event/trait.Source.html
365    /// [`readable`]: struct.Interest.html#associatedconstant.READABLE
366    /// [`writable`]: struct.Interest.html#associatedconstant.WRITABLE
367    /// [struct]: struct.Poll.html
368    /// [`iter`]: ./event/struct.Events.html#method.iter
369    ///
370    /// # Notes
371    ///
372    /// This returns any errors without attempting to retry, previous versions
373    /// of Mio would automatically retry the poll call if it was interrupted
374    /// (if `EINTR` was returned).
375    ///
376    /// Currently if the `timeout` elapses without any readiness events
377    /// triggering this will return `Ok(())`. However we're not guaranteeing
378    /// this behaviour as this depends on the OS.
379    ///
380    /// # Examples
381    ///
382    /// A basic example -- establishing a `TcpStream` connection.
383    ///
384    #[cfg_attr(all(feature = "os-poll", feature = "net"), doc = "```")]
385    #[cfg_attr(not(all(feature = "os-poll", feature = "net")), doc = "```ignore")]
386    /// # use std::error::Error;
387    /// # fn main() -> Result<(), Box<dyn Error>> {
388    /// use mio::{Events, Poll, Interest, Token};
389    /// use mio::net::TcpStream;
390    ///
391    /// use std::net::{TcpListener, SocketAddr};
392    /// use std::thread;
393    ///
394    /// // Bind a server socket to connect to.
395    /// let addr: SocketAddr = "127.0.0.1:0".parse()?;
396    /// let server = TcpListener::bind(addr)?;
397    /// let addr = server.local_addr()?.clone();
398    ///
399    /// // Spawn a thread to accept the socket
400    /// thread::spawn(move || {
401    ///     let _ = server.accept();
402    /// });
403    ///
404    /// // Construct a new `Poll` handle as well as the `Events` we'll store into
405    /// let mut poll = Poll::new()?;
406    /// let mut events = Events::with_capacity(1024);
407    ///
408    /// // Connect the stream
409    /// let mut stream = TcpStream::connect(addr)?;
410    ///
411    /// // Register the stream with `Poll`
412    /// poll.registry().register(
413    ///     &mut stream,
414    ///     Token(0),
415    ///     Interest::READABLE | Interest::WRITABLE)?;
416    ///
417    /// // Wait for the socket to become ready. This has to happens in a loop to
418    /// // handle spurious wakeups.
419    /// loop {
420    ///     poll.poll(&mut events, None)?;
421    ///
422    ///     for event in &events {
423    ///         if event.token() == Token(0) && event.is_writable() {
424    ///             // The socket connected (probably, it could still be a spurious
425    ///             // wakeup)
426    ///             return Ok(());
427    ///         }
428    ///     }
429    /// }
430    /// # }
431    /// ```
432    ///
433    /// [struct]: #
434    pub fn poll(&mut self, events: &mut Events, timeout: Option<Duration>) -> io::Result<()> {
435        self.registry.selector.select(events.sys(), timeout)
436    }
437}
438
439#[cfg(all(
440    unix,
441    not(mio_unsupported_force_poll_poll),
442    not(any(
443        target_os = "espidf",
444        target_os = "fuchsia",
445        target_os = "haiku",
446        target_os = "hermit",
447        target_os = "hurd",
448        target_os = "nto",
449        target_os = "solaris",
450        target_os = "vita"
451    )),
452))]
453impl AsRawFd for Poll {
454    fn as_raw_fd(&self) -> RawFd {
455        self.registry.as_raw_fd()
456    }
457}
458
459impl fmt::Debug for Poll {
460    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
461        fmt.debug_struct("Poll").finish()
462    }
463}
464
465impl Registry {
466    /// Register an [`event::Source`] with the `Poll` instance.
467    ///
468    /// Once registered, the `Poll` instance will monitor the event source for
469    /// readiness state changes. When it notices a state change, it will return
470    /// a readiness event for the handle the next time [`poll`] is called.
471    ///
472    /// See [`Poll`] docs for a high level overview.
473    ///
474    /// # Arguments
475    ///
476    /// `source: &mut S: event::Source`: This is the source of events that the
477    /// `Poll` instance should monitor for readiness state changes.
478    ///
479    /// `token: Token`: The caller picks a token to associate with the socket.
480    /// When [`poll`] returns an event for the handle, this token is included.
481    /// This allows the caller to map the event to its source. The token
482    /// associated with the `event::Source` can be changed at any time by
483    /// calling [`reregister`].
484    ///
485    /// See documentation on [`Token`] for an example showing how to pick
486    /// [`Token`] values.
487    ///
488    /// `interest: Interest`: Specifies which operations `Poll` should monitor
489    /// for readiness. `Poll` will only return readiness events for operations
490    /// specified by this argument.
491    ///
492    /// If a socket is registered with readable interest and the socket becomes
493    /// writable, no event will be returned from [`poll`].
494    ///
495    /// The readiness interest for an `event::Source` can be changed at any time
496    /// by calling [`reregister`].
497    ///
498    /// # Notes
499    ///
500    /// Callers must ensure that if a source being registered with a `Poll`
501    /// instance was previously registered with that `Poll` instance, then a
502    /// call to [`deregister`] has already occurred. Consecutive calls to
503    /// `register` is unspecified behavior.
504    ///
505    /// Unless otherwise specified, the caller should assume that once an event
506    /// source is registered with a `Poll` instance, it is bound to that `Poll`
507    /// instance for the lifetime of the event source. This remains true even
508    /// if the event source is deregistered from the poll instance using
509    /// [`deregister`].
510    ///
511    /// [`event::Source`]: ./event/trait.Source.html
512    /// [`poll`]: struct.Poll.html#method.poll
513    /// [`reregister`]: struct.Registry.html#method.reregister
514    /// [`deregister`]: struct.Registry.html#method.deregister
515    /// [`Token`]: struct.Token.html
516    ///
517    /// # Examples
518    ///
519    #[cfg_attr(all(feature = "os-poll", feature = "net"), doc = "```")]
520    #[cfg_attr(not(all(feature = "os-poll", feature = "net")), doc = "```ignore")]
521    /// # use std::error::Error;
522    /// # use std::net;
523    /// # fn main() -> Result<(), Box<dyn Error>> {
524    /// use mio::{Events, Poll, Interest, Token};
525    /// use mio::net::TcpStream;
526    /// use std::net::SocketAddr;
527    /// use std::time::{Duration, Instant};
528    ///
529    /// let mut poll = Poll::new()?;
530    ///
531    /// let address: SocketAddr = "127.0.0.1:0".parse()?;
532    /// let listener = net::TcpListener::bind(address)?;
533    /// let mut socket = TcpStream::connect(listener.local_addr()?)?;
534    ///
535    /// // Register the socket with `poll`
536    /// poll.registry().register(
537    ///     &mut socket,
538    ///     Token(0),
539    ///     Interest::READABLE | Interest::WRITABLE)?;
540    ///
541    /// let mut events = Events::with_capacity(1024);
542    /// let start = Instant::now();
543    /// let timeout = Duration::from_millis(500);
544    ///
545    /// loop {
546    ///     let elapsed = start.elapsed();
547    ///
548    ///     if elapsed >= timeout {
549    ///         // Connection timed out
550    ///         return Ok(());
551    ///     }
552    ///
553    ///     let remaining = timeout - elapsed;
554    ///     poll.poll(&mut events, Some(remaining))?;
555    ///
556    ///     for event in &events {
557    ///         if event.token() == Token(0) {
558    ///             // Something (probably) happened on the socket.
559    ///             return Ok(());
560    ///         }
561    ///     }
562    /// }
563    /// # }
564    /// ```
565    pub fn register<S>(&self, source: &mut S, token: Token, interests: Interest) -> io::Result<()>
566    where
567        S: event::Source + ?Sized,
568    {
569        trace!(
570            "registering event source with poller: token={:?}, interests={:?}",
571            token,
572            interests
573        );
574        source.register(self, token, interests)
575    }
576
577    /// Re-register an [`event::Source`] with the `Poll` instance.
578    ///
579    /// Re-registering an event source allows changing the details of the
580    /// registration. Specifically, it allows updating the associated `token`
581    /// and `interests` specified in previous `register` and `reregister` calls.
582    ///
583    /// The `reregister` arguments fully override the previous values. In other
584    /// words, if a socket is registered with [`readable`] interest and the call
585    /// to `reregister` specifies [`writable`], then read interest is no longer
586    /// requested for the handle.
587    ///
588    /// The event source must have previously been registered with this instance
589    /// of `Poll`, otherwise the behavior is unspecified.
590    ///
591    /// See the [`register`] documentation for details about the function
592    /// arguments and see the [`struct`] docs for a high level overview of
593    /// polling.
594    ///
595    /// # Examples
596    ///
597    #[cfg_attr(all(feature = "os-poll", feature = "net"), doc = "```")]
598    #[cfg_attr(not(all(feature = "os-poll", feature = "net")), doc = "```ignore")]
599    /// # use std::error::Error;
600    /// # use std::net;
601    /// # fn main() -> Result<(), Box<dyn Error>> {
602    /// use mio::{Poll, Interest, Token};
603    /// use mio::net::TcpStream;
604    /// use std::net::SocketAddr;
605    ///
606    /// let poll = Poll::new()?;
607    ///
608    /// let address: SocketAddr = "127.0.0.1:0".parse()?;
609    /// let listener = net::TcpListener::bind(address)?;
610    /// let mut socket = TcpStream::connect(listener.local_addr()?)?;
611    ///
612    /// // Register the socket with `poll`, requesting readable
613    /// poll.registry().register(
614    ///     &mut socket,
615    ///     Token(0),
616    ///     Interest::READABLE)?;
617    ///
618    /// // Reregister the socket specifying write interest instead. Even though
619    /// // the token is the same it must be specified.
620    /// poll.registry().reregister(
621    ///     &mut socket,
622    ///     Token(0),
623    ///     Interest::WRITABLE)?;
624    /// #     Ok(())
625    /// # }
626    /// ```
627    ///
628    /// [`event::Source`]: ./event/trait.Source.html
629    /// [`struct`]: struct.Poll.html
630    /// [`register`]: struct.Registry.html#method.register
631    /// [`readable`]: ./event/struct.Event.html#is_readable
632    /// [`writable`]: ./event/struct.Event.html#is_writable
633    pub fn reregister<S>(&self, source: &mut S, token: Token, interests: Interest) -> io::Result<()>
634    where
635        S: event::Source + ?Sized,
636    {
637        trace!(
638            "reregistering event source with poller: token={:?}, interests={:?}",
639            token,
640            interests
641        );
642        source.reregister(self, token, interests)
643    }
644
645    /// Deregister an [`event::Source`] with the `Poll` instance.
646    ///
647    /// When an event source is deregistered, the `Poll` instance will no longer
648    /// monitor it for readiness state changes. Deregistering clears up any
649    /// internal resources needed to track the handle.  After an explicit call
650    /// to this method completes, it is guaranteed that the token previously
651    /// registered to this handle will not be returned by a future poll, so long
652    /// as a happens-before relationship is established between this call and
653    /// the poll.
654    ///
655    /// The event source must have previously been registered with this instance
656    /// of `Poll`, otherwise the behavior is unspecified.
657    ///
658    /// A handle can be passed back to `register` after it has been
659    /// deregistered; however, it must be passed back to the **same** `Poll`
660    /// instance, otherwise the behavior is unspecified.
661    ///
662    /// # Examples
663    ///
664    #[cfg_attr(all(feature = "os-poll", feature = "net"), doc = "```")]
665    #[cfg_attr(not(all(feature = "os-poll", feature = "net")), doc = "```ignore")]
666    /// # use std::error::Error;
667    /// # use std::net;
668    /// # fn main() -> Result<(), Box<dyn Error>> {
669    /// use mio::{Events, Poll, Interest, Token};
670    /// use mio::net::TcpStream;
671    /// use std::net::SocketAddr;
672    /// use std::time::Duration;
673    ///
674    /// let mut poll = Poll::new()?;
675    ///
676    /// let address: SocketAddr = "127.0.0.1:0".parse()?;
677    /// let listener = net::TcpListener::bind(address)?;
678    /// let mut socket = TcpStream::connect(listener.local_addr()?)?;
679    ///
680    /// // Register the socket with `poll`
681    /// poll.registry().register(
682    ///     &mut socket,
683    ///     Token(0),
684    ///     Interest::READABLE)?;
685    ///
686    /// poll.registry().deregister(&mut socket)?;
687    ///
688    /// let mut events = Events::with_capacity(1024);
689    ///
690    /// // Set a timeout because this poll should never receive any events.
691    /// poll.poll(&mut events, Some(Duration::from_secs(1)))?;
692    /// assert!(events.is_empty());
693    /// #     Ok(())
694    /// # }
695    /// ```
696    pub fn deregister<S>(&self, source: &mut S) -> io::Result<()>
697    where
698        S: event::Source + ?Sized,
699    {
700        trace!("deregistering event source from poller");
701        source.deregister(self)
702    }
703
704    /// Creates a new independently owned `Registry`.
705    ///
706    /// Event sources registered with this `Registry` will be registered with
707    /// the original `Registry` and `Poll` instance.
708    pub fn try_clone(&self) -> io::Result<Registry> {
709        self.selector.try_clone().map(|selector| Registry {
710            selector,
711            #[cfg(all(debug_assertions, not(target_os = "wasi")))]
712            has_waker: Arc::clone(&self.has_waker),
713        })
714    }
715
716    /// Internal check to ensure only a single `Waker` is active per [`Poll`]
717    /// instance.
718    #[cfg(all(debug_assertions, not(target_os = "wasi")))]
719    pub(crate) fn register_waker(&self) {
720        assert!(
721            !self.has_waker.swap(true, Ordering::AcqRel),
722            "Only a single `Waker` can be active per `Poll` instance"
723        );
724    }
725
726    /// Get access to the `sys::Selector`.
727    #[cfg(any(not(target_os = "wasi"), feature = "net"))]
728    pub(crate) fn selector(&self) -> &sys::Selector {
729        &self.selector
730    }
731}
732
733impl fmt::Debug for Registry {
734    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
735        fmt.debug_struct("Registry").finish()
736    }
737}
738
739#[cfg(all(
740    unix,
741    not(mio_unsupported_force_poll_poll),
742    not(any(
743        target_os = "espidf",
744        target_os = "haiku",
745        target_os = "fuchsia",
746        target_os = "hermit",
747        target_os = "hurd",
748        target_os = "nto",
749        target_os = "solaris",
750        target_os = "vita"
751    )),
752))]
753impl AsRawFd for Registry {
754    fn as_raw_fd(&self) -> RawFd {
755        self.selector.as_raw_fd()
756    }
757}
758
759cfg_os_poll! {
760    #[cfg(all(
761        unix,
762        not(mio_unsupported_force_poll_poll),
763        not(any(
764            target_os = "espidf",
765            target_os = "hermit",
766            target_os = "hurd",
767            target_os = "nto",
768            target_os = "solaris",
769            target_os = "vita"
770        )),
771    ))]
772    #[test]
773    pub fn as_raw_fd() {
774        let poll = Poll::new().unwrap();
775        assert!(poll.as_raw_fd() > 0);
776    }
777}