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