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 = "fuchsia",
8        target_os = "haiku",
9        target_os = "hermit",
10        target_os = "hurd",
11        target_os = "nto",
12        target_os = "solaris",
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/// | Windows       | [IOCP]    |
247/// | macOS         | [kqueue]  |
248///
249/// On all supported platforms, socket operations are handled by using the
250/// system selector. Platform specific extensions (e.g. [`SourceFd`]) allow
251/// accessing other features provided by individual system selectors. For
252/// example, Linux's [`signalfd`] feature can be used by registering the FD with
253/// `Poll` via [`SourceFd`].
254///
255/// On all platforms except windows, a call to [`Poll::poll`] is mostly just a
256/// direct call to the system selector. However, [IOCP] uses a completion model
257/// instead of a readiness model. In this case, `Poll` must adapt the completion
258/// model Mio's API. While non-trivial, the bridge layer is still quite
259/// efficient. The most expensive part being calls to `read` and `write` require
260/// data to be copied into an intermediate buffer before it is passed to the
261/// kernel.
262///
263/// [epoll]: https://man7.org/linux/man-pages/man7/epoll.7.html
264/// [kqueue]: https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2
265/// [IOCP]: https://docs.microsoft.com/en-us/windows/win32/fileio/i-o-completion-ports
266/// [`signalfd`]: https://man7.org/linux/man-pages/man2/signalfd.2.html
267/// [`SourceFd`]: unix/struct.SourceFd.html
268/// [`Poll::poll`]: struct.Poll.html#method.poll
269pub struct Poll {
270    registry: Registry,
271}
272
273/// Registers I/O resources.
274pub struct Registry {
275    selector: sys::Selector,
276    /// Whether this selector currently has an associated waker.
277    #[cfg(all(debug_assertions, not(any(target_os = "wasi", target_os = "horizon"))))]
278    has_waker: Arc<AtomicBool>,
279}
280
281impl Poll {
282    cfg_os_poll! {
283        /// Return a new `Poll` handle.
284        ///
285        /// This function will make a syscall to the operating system to create
286        /// the system selector. If this syscall fails, `Poll::new` will return
287        /// with the error.
288        ///
289        /// close-on-exec flag is set on the file descriptors used by the selector to prevent
290        /// leaking it to executed processes. However, on some systems such as
291        /// old Linux systems that don't support `epoll_create1` syscall it is done
292        /// non-atomically, so a separate thread executing in parallel to this
293        /// function may accidentally leak the file descriptor if it executes a
294        /// new process before this function returns.
295        ///
296        /// See [struct] level docs for more details.
297        ///
298        /// [struct]: struct.Poll.html
299        ///
300        /// # Examples
301        ///
302        /// ```
303        /// # use std::error::Error;
304        /// # fn main() -> Result<(), Box<dyn Error>> {
305        /// use mio::{Poll, Events};
306        /// use std::time::Duration;
307        ///
308        /// let mut poll = match Poll::new() {
309        ///     Ok(poll) => poll,
310        ///     Err(e) => panic!("failed to create Poll instance; err={:?}", e),
311        /// };
312        ///
313        /// // Create a structure to receive polled events
314        /// let mut events = Events::with_capacity(1024);
315        ///
316        /// // Wait for events, but none will be received because no
317        /// // `event::Source`s have been registered with this `Poll` instance.
318        /// poll.poll(&mut events, Some(Duration::from_millis(500)))?;
319        /// assert!(events.is_empty());
320        /// #     Ok(())
321        /// # }
322        /// ```
323        pub fn new() -> io::Result<Poll> {
324            sys::Selector::new().map(|selector| Poll {
325                registry: Registry {
326                    selector,
327                    #[cfg(all(debug_assertions, not(any(target_os = "wasi", target_os = "horizon"))))]
328                    has_waker: Arc::new(AtomicBool::new(false)),
329                },
330            })
331        }
332    }
333
334    /// Returns a `Registry` which can be used to register
335    /// `event::Source`s.
336    pub fn registry(&self) -> &Registry {
337        &self.registry
338    }
339
340    /// Wait for readiness events
341    ///
342    /// Blocks the current thread and waits for readiness events for any of the
343    /// [`event::Source`]s that have been registered with this `Poll` instance.
344    /// The function will block until either at least one readiness event has
345    /// been received or `timeout` has elapsed. A `timeout` of `None` means that
346    /// `poll` will block until a readiness event has been received.
347    ///
348    /// The supplied `events` will be cleared and newly received readiness events
349    /// will be pushed onto the end. At most `events.capacity()` events will be
350    /// returned. If there are further pending readiness events, they will be
351    /// returned on the next call to `poll`.
352    ///
353    /// A single call to `poll` may result in multiple readiness events being
354    /// returned for a single event source. For example, if a TCP socket becomes
355    /// both readable and writable, it may be possible for a single readiness
356    /// event to be returned with both [`readable`] and [`writable`] readiness
357    /// **OR** two separate events may be returned, one with [`readable`] set
358    /// and one with [`writable`] set.
359    ///
360    /// Note that the `timeout` will be rounded up to the system clock
361    /// granularity (usually 1ms), and kernel scheduling delays mean that
362    /// the blocking interval may be overrun by a small amount. A timeout
363    /// of [`Duration::ZERO`] is not affected by this rounding.
364    ///
365    /// See the [struct] level documentation for a higher level discussion of
366    /// polling.
367    ///
368    /// [`event::Source`]: ./event/trait.Source.html
369    /// [`readable`]: struct.Interest.html#associatedconstant.READABLE
370    /// [`writable`]: struct.Interest.html#associatedconstant.WRITABLE
371    /// [struct]: struct.Poll.html
372    /// [`iter`]: ./event/struct.Events.html#method.iter
373    ///
374    /// # Notes
375    ///
376    /// This returns any errors without attempting to retry, previous versions
377    /// of Mio would automatically retry the poll call if it was interrupted
378    /// (if `EINTR` was returned).
379    ///
380    /// Currently if the `timeout` elapses without any readiness events
381    /// triggering this will return `Ok(())`. However we're not guaranteeing
382    /// this behaviour as this depends on the OS.
383    ///
384    /// # Examples
385    ///
386    /// A basic example -- establishing a `TcpStream` connection.
387    ///
388    #[cfg_attr(all(feature = "os-poll", feature = "net"), doc = "```")]
389    #[cfg_attr(not(all(feature = "os-poll", feature = "net")), doc = "```ignore")]
390    /// # use std::error::Error;
391    /// # fn main() -> Result<(), Box<dyn Error>> {
392    /// # // WASI does not yet support multithreading:
393    /// # if cfg!(target_os = "wasi") { return Ok(()) }
394    /// use mio::{Events, Poll, Interest, Token};
395    /// use mio::net::TcpStream;
396    ///
397    /// use std::net::{TcpListener, SocketAddr};
398    /// use std::thread;
399    ///
400    /// // Bind a server socket to connect to.
401    /// let addr: SocketAddr = "127.0.0.1:0".parse()?;
402    /// let server = TcpListener::bind(addr)?;
403    /// let addr = server.local_addr()?.clone();
404    ///
405    /// // Spawn a thread to accept the socket
406    /// thread::spawn(move || {
407    ///     let _ = server.accept();
408    /// });
409    ///
410    /// // Construct a new `Poll` handle as well as the `Events` we'll store into
411    /// let mut poll = Poll::new()?;
412    /// let mut events = Events::with_capacity(1024);
413    ///
414    /// // Connect the stream
415    /// let mut stream = TcpStream::connect(addr)?;
416    ///
417    /// // Register the stream with `Poll`
418    /// poll.registry().register(
419    ///     &mut stream,
420    ///     Token(0),
421    ///     Interest::READABLE | Interest::WRITABLE)?;
422    ///
423    /// // Wait for the socket to become ready. This has to happen in a loop to
424    /// // handle spurious wakeups.
425    /// loop {
426    ///     poll.poll(&mut events, None)?;
427    ///
428    ///     for event in &events {
429    ///         if event.token() == Token(0) && event.is_writable() {
430    ///             // The socket connected (probably, it could still be a spurious
431    ///             // wakeup)
432    ///             return Ok(());
433    ///         }
434    ///     }
435    /// }
436    /// # }
437    /// ```
438    ///
439    /// [struct]: #
440    pub fn poll(&mut self, events: &mut Events, timeout: Option<Duration>) -> io::Result<()> {
441        self.registry.selector.select(events.sys(), timeout)
442    }
443}
444
445#[cfg(all(
446    unix,
447    not(mio_unsupported_force_poll_poll),
448    not(any(
449        target_os = "aix",
450        target_os = "espidf",
451        target_os = "fuchsia",
452        target_os = "haiku",
453        target_os = "hermit",
454        target_os = "hurd",
455        target_os = "nto",
456        target_os = "solaris",
457        target_os = "vita",
458        target_os = "cygwin",
459        target_os = "horizon"
460    )),
461))]
462impl AsRawFd for Poll {
463    fn as_raw_fd(&self) -> RawFd {
464        self.registry.as_raw_fd()
465    }
466}
467
468impl fmt::Debug for Poll {
469    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
470        fmt.debug_struct("Poll").finish()
471    }
472}
473
474impl Registry {
475    /// Register an [`event::Source`] with the `Poll` instance.
476    ///
477    /// Once registered, the `Poll` instance will monitor the event source for
478    /// readiness state changes. When it notices a state change, it will return
479    /// a readiness event for the handle the next time [`poll`] is called.
480    ///
481    /// See [`Poll`] docs for a high level overview.
482    ///
483    /// # Arguments
484    ///
485    /// `source: &mut S: event::Source`: This is the source of events that the
486    /// `Poll` instance should monitor for readiness state changes.
487    ///
488    /// `token: Token`: The caller picks a token to associate with the socket.
489    /// When [`poll`] returns an event for the handle, this token is included.
490    /// This allows the caller to map the event to its source. The token
491    /// associated with the `event::Source` can be changed at any time by
492    /// calling [`reregister`].
493    ///
494    /// See documentation on [`Token`] for an example showing how to pick
495    /// [`Token`] values.
496    ///
497    /// `interest: Interest`: Specifies which operations `Poll` should monitor
498    /// for readiness. `Poll` will only return readiness events for operations
499    /// specified by this argument.
500    ///
501    /// If a socket is registered with readable interest and the socket becomes
502    /// writable, no event will be returned from [`poll`].
503    ///
504    /// The readiness interest for an `event::Source` can be changed at any time
505    /// by calling [`reregister`].
506    ///
507    /// # Notes
508    ///
509    /// Callers must ensure that if a source being registered with a `Poll`
510    /// instance was previously registered with that `Poll` instance, then a
511    /// call to [`deregister`] has already occurred. Consecutive calls to
512    /// `register` is unspecified behavior.
513    ///
514    /// Unless otherwise specified, the caller should assume that once an event
515    /// source is registered with a `Poll` instance, it is bound to that `Poll`
516    /// instance for the lifetime of the event source. This remains true even
517    /// if the event source is deregistered from the poll instance using
518    /// [`deregister`].
519    ///
520    /// [`event::Source`]: ./event/trait.Source.html
521    /// [`poll`]: struct.Poll.html#method.poll
522    /// [`reregister`]: struct.Registry.html#method.reregister
523    /// [`deregister`]: struct.Registry.html#method.deregister
524    /// [`Token`]: struct.Token.html
525    ///
526    /// # Examples
527    ///
528    #[cfg_attr(all(feature = "os-poll", feature = "net"), doc = "```")]
529    #[cfg_attr(not(all(feature = "os-poll", feature = "net")), doc = "```ignore")]
530    /// # use std::error::Error;
531    /// # use std::net;
532    /// # fn main() -> Result<(), Box<dyn Error>> {
533    /// use mio::{Events, Poll, Interest, Token};
534    /// use mio::net::TcpStream;
535    /// use std::net::SocketAddr;
536    /// use std::time::{Duration, Instant};
537    ///
538    /// let mut poll = Poll::new()?;
539    ///
540    /// let address: SocketAddr = "127.0.0.1:0".parse()?;
541    /// let listener = net::TcpListener::bind(address)?;
542    /// let mut socket = TcpStream::connect(listener.local_addr()?)?;
543    ///
544    /// // Register the socket with `poll`
545    /// poll.registry().register(
546    ///     &mut socket,
547    ///     Token(0),
548    ///     Interest::READABLE | Interest::WRITABLE)?;
549    ///
550    /// let mut events = Events::with_capacity(1024);
551    /// let start = Instant::now();
552    /// let timeout = Duration::from_millis(500);
553    ///
554    /// loop {
555    ///     let elapsed = start.elapsed();
556    ///
557    ///     if elapsed >= timeout {
558    ///         // Connection timed out
559    ///         return Ok(());
560    ///     }
561    ///
562    ///     let remaining = timeout - elapsed;
563    ///     poll.poll(&mut events, Some(remaining))?;
564    ///
565    ///     for event in &events {
566    ///         if event.token() == Token(0) {
567    ///             // Something (probably) happened on the socket.
568    ///             return Ok(());
569    ///         }
570    ///     }
571    /// }
572    /// # }
573    /// ```
574    pub fn register<S>(&self, source: &mut S, token: Token, interests: Interest) -> io::Result<()>
575    where
576        S: event::Source + ?Sized,
577    {
578        trace!(
579            "registering event source with poller: token={:?}, interests={:?}",
580            token,
581            interests
582        );
583        source.register(self, token, interests)
584    }
585
586    /// Re-register an [`event::Source`] with the `Poll` instance.
587    ///
588    /// Re-registering an event source allows changing the details of the
589    /// registration. Specifically, it allows updating the associated `token`
590    /// and `interests` specified in previous `register` and `reregister` calls.
591    ///
592    /// The `reregister` arguments fully override the previous values. In other
593    /// words, if a socket is registered with [`readable`] interest and the call
594    /// to `reregister` specifies [`writable`], then read interest is no longer
595    /// requested for the handle.
596    ///
597    /// The event source must have previously been registered with this instance
598    /// of `Poll`, otherwise the behavior is unspecified.
599    ///
600    /// See the [`register`] documentation for details about the function
601    /// arguments and see the [`struct`] docs for a high level overview of
602    /// polling.
603    ///
604    /// # Examples
605    ///
606    #[cfg_attr(all(feature = "os-poll", feature = "net"), doc = "```")]
607    #[cfg_attr(not(all(feature = "os-poll", feature = "net")), doc = "```ignore")]
608    /// # use std::error::Error;
609    /// # use std::net;
610    /// # fn main() -> Result<(), Box<dyn Error>> {
611    /// use mio::{Poll, Interest, Token};
612    /// use mio::net::TcpStream;
613    /// use std::net::SocketAddr;
614    ///
615    /// let poll = Poll::new()?;
616    ///
617    /// let address: SocketAddr = "127.0.0.1:0".parse()?;
618    /// let listener = net::TcpListener::bind(address)?;
619    /// let mut socket = TcpStream::connect(listener.local_addr()?)?;
620    ///
621    /// // Register the socket with `poll`, requesting readable
622    /// poll.registry().register(
623    ///     &mut socket,
624    ///     Token(0),
625    ///     Interest::READABLE)?;
626    ///
627    /// // Reregister the socket specifying write interest instead. Even though
628    /// // the token is the same it must be specified.
629    /// poll.registry().reregister(
630    ///     &mut socket,
631    ///     Token(0),
632    ///     Interest::WRITABLE)?;
633    /// #     Ok(())
634    /// # }
635    /// ```
636    ///
637    /// [`event::Source`]: ./event/trait.Source.html
638    /// [`struct`]: struct.Poll.html
639    /// [`register`]: struct.Registry.html#method.register
640    /// [`readable`]: ./event/struct.Event.html#is_readable
641    /// [`writable`]: ./event/struct.Event.html#is_writable
642    pub fn reregister<S>(&self, source: &mut S, token: Token, interests: Interest) -> io::Result<()>
643    where
644        S: event::Source + ?Sized,
645    {
646        trace!(
647            "reregistering event source with poller: token={:?}, interests={:?}",
648            token,
649            interests
650        );
651        source.reregister(self, token, interests)
652    }
653
654    /// Deregister an [`event::Source`] with the `Poll` instance.
655    ///
656    /// When an event source is deregistered, the `Poll` instance will no longer
657    /// monitor it for readiness state changes. Deregistering clears up any
658    /// internal resources needed to track the handle.  After an explicit call
659    /// to this method completes, it is guaranteed that the token previously
660    /// registered to this handle will not be returned by a future poll, so long
661    /// as a happens-before relationship is established between this call and
662    /// the poll.
663    ///
664    /// The event source must have previously been registered with this instance
665    /// of `Poll`, otherwise the behavior is unspecified.
666    ///
667    /// A handle can be passed back to `register` after it has been
668    /// deregistered; however, it must be passed back to the **same** `Poll`
669    /// instance, otherwise the behavior is unspecified.
670    ///
671    /// # Examples
672    ///
673    #[cfg_attr(all(feature = "os-poll", feature = "net"), doc = "```")]
674    #[cfg_attr(not(all(feature = "os-poll", feature = "net")), doc = "```ignore")]
675    /// # use std::error::Error;
676    /// # use std::net;
677    /// # fn main() -> Result<(), Box<dyn Error>> {
678    /// use mio::{Events, Poll, Interest, Token};
679    /// use mio::net::TcpStream;
680    /// use std::net::SocketAddr;
681    /// use std::time::Duration;
682    ///
683    /// let mut poll = Poll::new()?;
684    ///
685    /// let address: SocketAddr = "127.0.0.1:0".parse()?;
686    /// let listener = net::TcpListener::bind(address)?;
687    /// let mut socket = TcpStream::connect(listener.local_addr()?)?;
688    ///
689    /// // Register the socket with `poll`
690    /// poll.registry().register(
691    ///     &mut socket,
692    ///     Token(0),
693    ///     Interest::READABLE)?;
694    ///
695    /// poll.registry().deregister(&mut socket)?;
696    ///
697    /// let mut events = Events::with_capacity(1024);
698    ///
699    /// // Set a timeout because this poll should never receive any events.
700    /// poll.poll(&mut events, Some(Duration::from_secs(1)))?;
701    /// assert!(events.is_empty());
702    /// #     Ok(())
703    /// # }
704    /// ```
705    pub fn deregister<S>(&self, source: &mut S) -> io::Result<()>
706    where
707        S: event::Source + ?Sized,
708    {
709        trace!("deregistering event source from poller");
710        source.deregister(self)
711    }
712
713    /// Creates a new independently owned `Registry`.
714    ///
715    /// Event sources registered with this `Registry` will be registered with
716    /// the original `Registry` and `Poll` instance.
717    pub fn try_clone(&self) -> io::Result<Registry> {
718        self.selector.try_clone().map(|selector| Registry {
719            selector,
720            #[cfg(all(debug_assertions, not(any(target_os = "wasi", target_os = "horizon"))))]
721            has_waker: Arc::clone(&self.has_waker),
722        })
723    }
724
725    /// Internal check to ensure only a single `Waker` is active per [`Poll`]
726    /// instance.
727    #[cfg(all(debug_assertions, not(any(target_os = "wasi", target_os = "horizon"))))]
728    pub(crate) fn register_waker(&self) {
729        assert!(
730            !self.has_waker.swap(true, Ordering::AcqRel),
731            "Only a single `Waker` can be active per `Poll` instance"
732        );
733    }
734
735    /// Get access to the `sys::Selector`.
736    #[cfg(any(not(target_os = "wasi"), feature = "net"))]
737    #[cfg_attr(target_os = "horizon", allow(dead_code))]
738    pub(crate) fn selector(&self) -> &sys::Selector {
739        &self.selector
740    }
741}
742
743impl fmt::Debug for Registry {
744    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
745        fmt.debug_struct("Registry").finish()
746    }
747}
748
749#[cfg(all(
750    unix,
751    not(mio_unsupported_force_poll_poll),
752    not(any(
753        target_os = "aix",
754        target_os = "espidf",
755        target_os = "haiku",
756        target_os = "fuchsia",
757        target_os = "hermit",
758        target_os = "hurd",
759        target_os = "nto",
760        target_os = "solaris",
761        target_os = "vita",
762        target_os = "cygwin",
763        target_os = "horizon"
764    )),
765))]
766impl AsFd for Registry {
767    fn as_fd(&self) -> BorrowedFd<'_> {
768        self.selector.as_fd()
769    }
770}
771
772#[cfg(all(
773    unix,
774    not(mio_unsupported_force_poll_poll),
775    not(any(
776        target_os = "aix",
777        target_os = "espidf",
778        target_os = "haiku",
779        target_os = "fuchsia",
780        target_os = "hermit",
781        target_os = "hurd",
782        target_os = "nto",
783        target_os = "solaris",
784        target_os = "vita",
785        target_os = "cygwin",
786        target_os = "horizon"
787    )),
788))]
789impl AsRawFd for Registry {
790    fn as_raw_fd(&self) -> RawFd {
791        self.selector.as_raw_fd()
792    }
793}
794
795cfg_os_poll! {
796    #[cfg(all(
797        unix,
798        not(mio_unsupported_force_poll_poll),
799        not(any(
800            target_os = "aix",
801            target_os = "espidf",
802            target_os = "hermit",
803            target_os = "hurd",
804            target_os = "nto",
805            target_os = "solaris",
806            target_os = "vita",
807            target_os = "cygwin",
808            target_os = "horizon"
809        )),
810    ))]
811    #[test]
812    pub fn as_raw_fd() {
813        let poll = Poll::new().unwrap();
814        assert!(poll.as_raw_fd() > 0);
815    }
816}