Skip to main content

mio/
poll.rs

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