Coverage Report

Created: 2026-03-31 07:04

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/mio-1.2.0/src/poll.rs
Line
Count
Source
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
))]
17
use std::os::fd::{AsFd, AsRawFd, BorrowedFd, RawFd};
18
#[cfg(all(debug_assertions, not(target_os = "wasi")))]
19
use std::sync::atomic::{AtomicBool, Ordering};
20
#[cfg(all(debug_assertions, not(target_os = "wasi")))]
21
use std::sync::Arc;
22
use std::time::Duration;
23
use std::{fmt, io};
24
25
use 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
268
pub struct Poll {
269
    registry: Registry,
270
}
271
272
/// Registers I/O resources.
273
pub 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
280
impl 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
0
        pub fn new() -> io::Result<Poll> {
323
0
            sys::Selector::new().map(|selector| Poll {
324
0
                registry: Registry {
325
0
                    selector,
326
0
                    #[cfg(all(debug_assertions, not(target_os = "wasi")))]
327
0
                    has_waker: Arc::new(AtomicBool::new(false)),
328
0
                },
329
0
            })
330
0
        }
331
    }
332
333
    /// Returns a `Registry` which can be used to register
334
    /// `event::Source`s.
335
0
    pub fn registry(&self) -> &Registry {
336
0
        &self.registry
337
0
    }
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. A timeout
362
    /// of [`Duration::ZERO`] is not affected by this rounding.
363
    ///
364
    /// See the [struct] level documentation for a higher level discussion of
365
    /// polling.
366
    ///
367
    /// [`event::Source`]: ./event/trait.Source.html
368
    /// [`readable`]: struct.Interest.html#associatedconstant.READABLE
369
    /// [`writable`]: struct.Interest.html#associatedconstant.WRITABLE
370
    /// [struct]: struct.Poll.html
371
    /// [`iter`]: ./event/struct.Events.html#method.iter
372
    ///
373
    /// # Notes
374
    ///
375
    /// This returns any errors without attempting to retry, previous versions
376
    /// of Mio would automatically retry the poll call if it was interrupted
377
    /// (if `EINTR` was returned).
378
    ///
379
    /// Currently if the `timeout` elapses without any readiness events
380
    /// triggering this will return `Ok(())`. However we're not guaranteeing
381
    /// this behaviour as this depends on the OS.
382
    ///
383
    /// # Examples
384
    ///
385
    /// A basic example -- establishing a `TcpStream` connection.
386
    ///
387
    #[cfg_attr(all(feature = "os-poll", feature = "net"), doc = "```")]
388
    #[cfg_attr(not(all(feature = "os-poll", feature = "net")), doc = "```ignore")]
389
    /// # use std::error::Error;
390
    /// # fn main() -> Result<(), Box<dyn Error>> {
391
    /// # // WASI does not yet support multithreading:
392
    /// # if cfg!(target_os = "wasi") { return Ok(()) }
393
    /// use mio::{Events, Poll, Interest, Token};
394
    /// use mio::net::TcpStream;
395
    ///
396
    /// use std::net::{TcpListener, SocketAddr};
397
    /// use std::thread;
398
    ///
399
    /// // Bind a server socket to connect to.
400
    /// let addr: SocketAddr = "127.0.0.1:0".parse()?;
401
    /// let server = TcpListener::bind(addr)?;
402
    /// let addr = server.local_addr()?.clone();
403
    ///
404
    /// // Spawn a thread to accept the socket
405
    /// thread::spawn(move || {
406
    ///     let _ = server.accept();
407
    /// });
408
    ///
409
    /// // Construct a new `Poll` handle as well as the `Events` we'll store into
410
    /// let mut poll = Poll::new()?;
411
    /// let mut events = Events::with_capacity(1024);
412
    ///
413
    /// // Connect the stream
414
    /// let mut stream = TcpStream::connect(addr)?;
415
    ///
416
    /// // Register the stream with `Poll`
417
    /// poll.registry().register(
418
    ///     &mut stream,
419
    ///     Token(0),
420
    ///     Interest::READABLE | Interest::WRITABLE)?;
421
    ///
422
    /// // Wait for the socket to become ready. This has to happens in a loop to
423
    /// // handle spurious wakeups.
424
    /// loop {
425
    ///     poll.poll(&mut events, None)?;
426
    ///
427
    ///     for event in &events {
428
    ///         if event.token() == Token(0) && event.is_writable() {
429
    ///             // The socket connected (probably, it could still be a spurious
430
    ///             // wakeup)
431
    ///             return Ok(());
432
    ///         }
433
    ///     }
434
    /// }
435
    /// # }
436
    /// ```
437
    ///
438
    /// [struct]: #
439
0
    pub fn poll(&mut self, events: &mut Events, timeout: Option<Duration>) -> io::Result<()> {
440
0
        self.registry.selector.select(events.sys(), timeout)
441
0
    }
442
}
443
444
#[cfg(all(
445
    unix,
446
    not(mio_unsupported_force_poll_poll),
447
    not(any(
448
        target_os = "aix",
449
        target_os = "espidf",
450
        target_os = "fuchsia",
451
        target_os = "haiku",
452
        target_os = "hermit",
453
        target_os = "hurd",
454
        target_os = "nto",
455
        target_os = "solaris",
456
        target_os = "vita",
457
        target_os = "cygwin",
458
    )),
459
))]
460
impl AsRawFd for Poll {
461
0
    fn as_raw_fd(&self) -> RawFd {
462
0
        self.registry.as_raw_fd()
463
0
    }
464
}
465
466
impl fmt::Debug for Poll {
467
0
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
468
0
        fmt.debug_struct("Poll").finish()
469
0
    }
470
}
471
472
impl Registry {
473
    /// Register an [`event::Source`] with the `Poll` instance.
474
    ///
475
    /// Once registered, the `Poll` instance will monitor the event source for
476
    /// readiness state changes. When it notices a state change, it will return
477
    /// a readiness event for the handle the next time [`poll`] is called.
478
    ///
479
    /// See [`Poll`] docs for a high level overview.
480
    ///
481
    /// # Arguments
482
    ///
483
    /// `source: &mut S: event::Source`: This is the source of events that the
484
    /// `Poll` instance should monitor for readiness state changes.
485
    ///
486
    /// `token: Token`: The caller picks a token to associate with the socket.
487
    /// When [`poll`] returns an event for the handle, this token is included.
488
    /// This allows the caller to map the event to its source. The token
489
    /// associated with the `event::Source` can be changed at any time by
490
    /// calling [`reregister`].
491
    ///
492
    /// See documentation on [`Token`] for an example showing how to pick
493
    /// [`Token`] values.
494
    ///
495
    /// `interest: Interest`: Specifies which operations `Poll` should monitor
496
    /// for readiness. `Poll` will only return readiness events for operations
497
    /// specified by this argument.
498
    ///
499
    /// If a socket is registered with readable interest and the socket becomes
500
    /// writable, no event will be returned from [`poll`].
501
    ///
502
    /// The readiness interest for an `event::Source` can be changed at any time
503
    /// by calling [`reregister`].
504
    ///
505
    /// # Notes
506
    ///
507
    /// Callers must ensure that if a source being registered with a `Poll`
508
    /// instance was previously registered with that `Poll` instance, then a
509
    /// call to [`deregister`] has already occurred. Consecutive calls to
510
    /// `register` is unspecified behavior.
511
    ///
512
    /// Unless otherwise specified, the caller should assume that once an event
513
    /// source is registered with a `Poll` instance, it is bound to that `Poll`
514
    /// instance for the lifetime of the event source. This remains true even
515
    /// if the event source is deregistered from the poll instance using
516
    /// [`deregister`].
517
    ///
518
    /// [`event::Source`]: ./event/trait.Source.html
519
    /// [`poll`]: struct.Poll.html#method.poll
520
    /// [`reregister`]: struct.Registry.html#method.reregister
521
    /// [`deregister`]: struct.Registry.html#method.deregister
522
    /// [`Token`]: struct.Token.html
523
    ///
524
    /// # Examples
525
    ///
526
    #[cfg_attr(all(feature = "os-poll", feature = "net"), doc = "```")]
527
    #[cfg_attr(not(all(feature = "os-poll", feature = "net")), doc = "```ignore")]
528
    /// # use std::error::Error;
529
    /// # use std::net;
530
    /// # fn main() -> Result<(), Box<dyn Error>> {
531
    /// use mio::{Events, Poll, Interest, Token};
532
    /// use mio::net::TcpStream;
533
    /// use std::net::SocketAddr;
534
    /// use std::time::{Duration, Instant};
535
    ///
536
    /// let mut poll = Poll::new()?;
537
    ///
538
    /// let address: SocketAddr = "127.0.0.1:0".parse()?;
539
    /// let listener = net::TcpListener::bind(address)?;
540
    /// let mut socket = TcpStream::connect(listener.local_addr()?)?;
541
    ///
542
    /// // Register the socket with `poll`
543
    /// poll.registry().register(
544
    ///     &mut socket,
545
    ///     Token(0),
546
    ///     Interest::READABLE | Interest::WRITABLE)?;
547
    ///
548
    /// let mut events = Events::with_capacity(1024);
549
    /// let start = Instant::now();
550
    /// let timeout = Duration::from_millis(500);
551
    ///
552
    /// loop {
553
    ///     let elapsed = start.elapsed();
554
    ///
555
    ///     if elapsed >= timeout {
556
    ///         // Connection timed out
557
    ///         return Ok(());
558
    ///     }
559
    ///
560
    ///     let remaining = timeout - elapsed;
561
    ///     poll.poll(&mut events, Some(remaining))?;
562
    ///
563
    ///     for event in &events {
564
    ///         if event.token() == Token(0) {
565
    ///             // Something (probably) happened on the socket.
566
    ///             return Ok(());
567
    ///         }
568
    ///     }
569
    /// }
570
    /// # }
571
    /// ```
572
0
    pub fn register<S>(&self, source: &mut S, token: Token, interests: Interest) -> io::Result<()>
573
0
    where
574
0
        S: event::Source + ?Sized,
575
    {
576
0
        trace!(
577
            "registering event source with poller: token={:?}, interests={:?}",
578
0
            token,
579
0
            interests
580
        );
581
0
        source.register(self, token, interests)
582
0
    }
Unexecuted instantiation: <mio::poll::Registry>::register::<mio::net::udp::UdpSocket>
Unexecuted instantiation: <mio::poll::Registry>::register::<tokio::process::imp::Pipe>
Unexecuted instantiation: <mio::poll::Registry>::register::<mio::net::tcp::stream::TcpStream>
Unexecuted instantiation: <mio::poll::Registry>::register::<mio::net::tcp::listener::TcpListener>
Unexecuted instantiation: <mio::poll::Registry>::register::<mio::net::uds::stream::UnixStream>
Unexecuted instantiation: <mio::poll::Registry>::register::<mio::net::uds::datagram::UnixDatagram>
Unexecuted instantiation: <mio::poll::Registry>::register::<mio::net::uds::listener::UnixListener>
Unexecuted instantiation: <mio::poll::Registry>::register::<mio::sys::unix::pipe::Sender>
Unexecuted instantiation: <mio::poll::Registry>::register::<mio::sys::unix::pipe::Receiver>
Unexecuted instantiation: <mio::poll::Registry>::register::<tokio::process::imp::pidfd_reaper::Pidfd>
Unexecuted instantiation: <mio::poll::Registry>::register::<_>
583
584
    /// Re-register an [`event::Source`] with the `Poll` instance.
585
    ///
586
    /// Re-registering an event source allows changing the details of the
587
    /// registration. Specifically, it allows updating the associated `token`
588
    /// and `interests` specified in previous `register` and `reregister` calls.
589
    ///
590
    /// The `reregister` arguments fully override the previous values. In other
591
    /// words, if a socket is registered with [`readable`] interest and the call
592
    /// to `reregister` specifies [`writable`], then read interest is no longer
593
    /// requested for the handle.
594
    ///
595
    /// The event source must have previously been registered with this instance
596
    /// of `Poll`, otherwise the behavior is unspecified.
597
    ///
598
    /// See the [`register`] documentation for details about the function
599
    /// arguments and see the [`struct`] docs for a high level overview of
600
    /// polling.
601
    ///
602
    /// # Examples
603
    ///
604
    #[cfg_attr(all(feature = "os-poll", feature = "net"), doc = "```")]
605
    #[cfg_attr(not(all(feature = "os-poll", feature = "net")), doc = "```ignore")]
606
    /// # use std::error::Error;
607
    /// # use std::net;
608
    /// # fn main() -> Result<(), Box<dyn Error>> {
609
    /// use mio::{Poll, Interest, Token};
610
    /// use mio::net::TcpStream;
611
    /// use std::net::SocketAddr;
612
    ///
613
    /// let poll = Poll::new()?;
614
    ///
615
    /// let address: SocketAddr = "127.0.0.1:0".parse()?;
616
    /// let listener = net::TcpListener::bind(address)?;
617
    /// let mut socket = TcpStream::connect(listener.local_addr()?)?;
618
    ///
619
    /// // Register the socket with `poll`, requesting readable
620
    /// poll.registry().register(
621
    ///     &mut socket,
622
    ///     Token(0),
623
    ///     Interest::READABLE)?;
624
    ///
625
    /// // Reregister the socket specifying write interest instead. Even though
626
    /// // the token is the same it must be specified.
627
    /// poll.registry().reregister(
628
    ///     &mut socket,
629
    ///     Token(0),
630
    ///     Interest::WRITABLE)?;
631
    /// #     Ok(())
632
    /// # }
633
    /// ```
634
    ///
635
    /// [`event::Source`]: ./event/trait.Source.html
636
    /// [`struct`]: struct.Poll.html
637
    /// [`register`]: struct.Registry.html#method.register
638
    /// [`readable`]: ./event/struct.Event.html#is_readable
639
    /// [`writable`]: ./event/struct.Event.html#is_writable
640
0
    pub fn reregister<S>(&self, source: &mut S, token: Token, interests: Interest) -> io::Result<()>
641
0
    where
642
0
        S: event::Source + ?Sized,
643
    {
644
0
        trace!(
645
            "reregistering event source with poller: token={:?}, interests={:?}",
646
0
            token,
647
0
            interests
648
        );
649
0
        source.reregister(self, token, interests)
650
0
    }
651
652
    /// Deregister an [`event::Source`] with the `Poll` instance.
653
    ///
654
    /// When an event source is deregistered, the `Poll` instance will no longer
655
    /// monitor it for readiness state changes. Deregistering clears up any
656
    /// internal resources needed to track the handle.  After an explicit call
657
    /// to this method completes, it is guaranteed that the token previously
658
    /// registered to this handle will not be returned by a future poll, so long
659
    /// as a happens-before relationship is established between this call and
660
    /// the poll.
661
    ///
662
    /// The event source must have previously been registered with this instance
663
    /// of `Poll`, otherwise the behavior is unspecified.
664
    ///
665
    /// A handle can be passed back to `register` after it has been
666
    /// deregistered; however, it must be passed back to the **same** `Poll`
667
    /// instance, otherwise the behavior is unspecified.
668
    ///
669
    /// # Examples
670
    ///
671
    #[cfg_attr(all(feature = "os-poll", feature = "net"), doc = "```")]
672
    #[cfg_attr(not(all(feature = "os-poll", feature = "net")), doc = "```ignore")]
673
    /// # use std::error::Error;
674
    /// # use std::net;
675
    /// # fn main() -> Result<(), Box<dyn Error>> {
676
    /// use mio::{Events, Poll, Interest, Token};
677
    /// use mio::net::TcpStream;
678
    /// use std::net::SocketAddr;
679
    /// use std::time::Duration;
680
    ///
681
    /// let mut poll = Poll::new()?;
682
    ///
683
    /// let address: SocketAddr = "127.0.0.1:0".parse()?;
684
    /// let listener = net::TcpListener::bind(address)?;
685
    /// let mut socket = TcpStream::connect(listener.local_addr()?)?;
686
    ///
687
    /// // Register the socket with `poll`
688
    /// poll.registry().register(
689
    ///     &mut socket,
690
    ///     Token(0),
691
    ///     Interest::READABLE)?;
692
    ///
693
    /// poll.registry().deregister(&mut socket)?;
694
    ///
695
    /// let mut events = Events::with_capacity(1024);
696
    ///
697
    /// // Set a timeout because this poll should never receive any events.
698
    /// poll.poll(&mut events, Some(Duration::from_secs(1)))?;
699
    /// assert!(events.is_empty());
700
    /// #     Ok(())
701
    /// # }
702
    /// ```
703
0
    pub fn deregister<S>(&self, source: &mut S) -> io::Result<()>
704
0
    where
705
0
        S: event::Source + ?Sized,
706
    {
707
0
        trace!("deregistering event source from poller");
708
0
        source.deregister(self)
709
0
    }
Unexecuted instantiation: <mio::poll::Registry>::deregister::<mio::net::udp::UdpSocket>
Unexecuted instantiation: <mio::poll::Registry>::deregister::<tokio::process::imp::Pipe>
Unexecuted instantiation: <mio::poll::Registry>::deregister::<mio::net::tcp::stream::TcpStream>
Unexecuted instantiation: <mio::poll::Registry>::deregister::<mio::net::tcp::listener::TcpListener>
Unexecuted instantiation: <mio::poll::Registry>::deregister::<mio::net::uds::stream::UnixStream>
Unexecuted instantiation: <mio::poll::Registry>::deregister::<mio::net::uds::datagram::UnixDatagram>
Unexecuted instantiation: <mio::poll::Registry>::deregister::<mio::net::uds::listener::UnixListener>
Unexecuted instantiation: <mio::poll::Registry>::deregister::<mio::sys::unix::pipe::Sender>
Unexecuted instantiation: <mio::poll::Registry>::deregister::<mio::sys::unix::pipe::Receiver>
Unexecuted instantiation: <mio::poll::Registry>::deregister::<tokio::process::imp::pidfd_reaper::Pidfd>
Unexecuted instantiation: <mio::poll::Registry>::deregister::<_>
710
711
    /// Creates a new independently owned `Registry`.
712
    ///
713
    /// Event sources registered with this `Registry` will be registered with
714
    /// the original `Registry` and `Poll` instance.
715
0
    pub fn try_clone(&self) -> io::Result<Registry> {
716
0
        self.selector.try_clone().map(|selector| Registry {
717
0
            selector,
718
            #[cfg(all(debug_assertions, not(target_os = "wasi")))]
719
            has_waker: Arc::clone(&self.has_waker),
720
0
        })
721
0
    }
722
723
    /// Internal check to ensure only a single `Waker` is active per [`Poll`]
724
    /// instance.
725
    #[cfg(all(debug_assertions, not(target_os = "wasi")))]
726
    pub(crate) fn register_waker(&self) {
727
        assert!(
728
            !self.has_waker.swap(true, Ordering::AcqRel),
729
            "Only a single `Waker` can be active per `Poll` instance"
730
        );
731
    }
732
733
    /// Get access to the `sys::Selector`.
734
    #[cfg(any(not(target_os = "wasi"), feature = "net"))]
735
0
    pub(crate) fn selector(&self) -> &sys::Selector {
736
0
        &self.selector
737
0
    }
738
}
739
740
impl fmt::Debug for Registry {
741
0
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
742
0
        fmt.debug_struct("Registry").finish()
743
0
    }
744
}
745
746
#[cfg(all(
747
    unix,
748
    not(mio_unsupported_force_poll_poll),
749
    not(any(
750
        target_os = "aix",
751
        target_os = "espidf",
752
        target_os = "haiku",
753
        target_os = "fuchsia",
754
        target_os = "hermit",
755
        target_os = "hurd",
756
        target_os = "nto",
757
        target_os = "solaris",
758
        target_os = "vita",
759
        target_os = "cygwin",
760
    )),
761
))]
762
impl AsFd for Registry {
763
0
    fn as_fd(&self) -> BorrowedFd<'_> {
764
0
        self.selector.as_fd()
765
0
    }
766
}
767
768
#[cfg(all(
769
    unix,
770
    not(mio_unsupported_force_poll_poll),
771
    not(any(
772
        target_os = "aix",
773
        target_os = "espidf",
774
        target_os = "haiku",
775
        target_os = "fuchsia",
776
        target_os = "hermit",
777
        target_os = "hurd",
778
        target_os = "nto",
779
        target_os = "solaris",
780
        target_os = "vita",
781
        target_os = "cygwin",
782
    )),
783
))]
784
impl AsRawFd for Registry {
785
0
    fn as_raw_fd(&self) -> RawFd {
786
0
        self.selector.as_raw_fd()
787
0
    }
788
}
789
790
cfg_os_poll! {
791
    #[cfg(all(
792
        unix,
793
        not(mio_unsupported_force_poll_poll),
794
        not(any(
795
            target_os = "aix",
796
            target_os = "espidf",
797
            target_os = "hermit",
798
            target_os = "hurd",
799
            target_os = "nto",
800
            target_os = "solaris",
801
            target_os = "vita",
802
            target_os = "cygwin",
803
        )),
804
    ))]
805
    #[test]
806
    pub fn as_raw_fd() {
807
        let poll = Poll::new().unwrap();
808
        assert!(poll.as_raw_fd() > 0);
809
    }
810
}