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