Coverage Report

Created: 2026-09-14 06:40

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/mio-1.2.3/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 = "nuttx",
8
        target_os = "fuchsia",
9
        target_os = "haiku",
10
        target_os = "hermit",
11
        target_os = "hurd",
12
        target_os = "nto",
13
        target_os = "vita",
14
        target_os = "cygwin",
15
        target_os = "horizon"
16
    )),
17
))]
18
use std::os::fd::{AsFd, AsRawFd, BorrowedFd, RawFd};
19
#[cfg(all(debug_assertions, not(any(target_os = "wasi", target_os = "horizon"))))]
20
use std::sync::atomic::{AtomicBool, Ordering};
21
#[cfg(all(debug_assertions, not(any(target_os = "wasi", target_os = "horizon"))))]
22
use std::sync::Arc;
23
use std::time::Duration;
24
use std::{fmt, io};
25
26
use crate::{event, sys, Events, Interest, Token};
27
28
/// Polls for readiness events on all registered values.
29
///
30
/// `Poll` allows a program to monitor a large number of [`event::Source`]s,
31
/// waiting until one or more become "ready" for some class of operations; e.g.
32
/// reading and writing. An event source is considered ready if it is possible
33
/// to immediately perform a corresponding operation; e.g. [`read`] or
34
/// [`write`].
35
///
36
/// To use `Poll`, an `event::Source` must first be registered with the `Poll`
37
/// instance using the [`register`] method on its associated `Register`,
38
/// supplying readiness interest. The readiness interest tells `Poll` which
39
/// specific operations on the handle to monitor for readiness. A `Token` is
40
/// also passed to the [`register`] function. When `Poll` returns a readiness
41
/// event, it will include this token.  This associates the event with the
42
/// event source that generated the event.
43
///
44
/// [`event::Source`]: ./event/trait.Source.html
45
/// [`read`]: ./net/struct.TcpStream.html#method.read
46
/// [`write`]: ./net/struct.TcpStream.html#method.write
47
/// [`register`]: struct.Registry.html#method.register
48
///
49
/// # Examples
50
///
51
/// A basic example -- establishing a `TcpStream` connection.
52
///
53
#[cfg_attr(all(feature = "os-poll", feature = "net"), doc = "```")]
54
#[cfg_attr(not(all(feature = "os-poll", feature = "net")), doc = "```ignore")]
55
/// # use std::error::Error;
56
/// # fn main() -> Result<(), Box<dyn Error>> {
57
/// use mio::{Events, Poll, Interest, Token};
58
/// use mio::net::TcpStream;
59
///
60
/// use std::net::{self, SocketAddr};
61
///
62
/// // Bind a server socket to connect to.
63
/// let addr: SocketAddr = "127.0.0.1:0".parse()?;
64
/// let server = net::TcpListener::bind(addr)?;
65
///
66
/// // Construct a new `Poll` handle as well as the `Events` we'll store into
67
/// let mut poll = Poll::new()?;
68
/// let mut events = Events::with_capacity(1024);
69
///
70
/// // Connect the stream
71
/// let mut stream = TcpStream::connect(server.local_addr()?)?;
72
///
73
/// // Register the stream with `Poll`
74
/// poll.registry().register(&mut stream, Token(0), Interest::READABLE | Interest::WRITABLE)?;
75
///
76
/// // Wait for the socket to become ready. This has to happen in a loop to
77
/// // handle spurious wakeups.
78
/// loop {
79
///     poll.poll(&mut events, None)?;
80
///
81
///     for event in &events {
82
///         if event.token() == Token(0) && event.is_writable() {
83
///             // The socket connected (probably, it could still be a spurious
84
///             // wakeup)
85
///             return Ok(());
86
///         }
87
///     }
88
/// }
89
/// # }
90
/// ```
91
///
92
/// # Portability
93
///
94
/// Using `Poll` provides a portable interface across supported platforms as
95
/// long as the caller takes the following into consideration:
96
///
97
/// ### Spurious events
98
///
99
/// [`Poll::poll`] may return readiness events even if the associated
100
/// event source is not actually ready. Given the same code, this may
101
/// happen more on some platforms than others. It is important to never assume
102
/// that, just because a readiness event was received, that the associated
103
/// operation will succeed as well.
104
///
105
/// If operation fails with [`WouldBlock`], then the caller should not treat
106
/// this as an error, but instead should wait until another readiness event is
107
/// received.
108
///
109
/// ### Draining readiness
110
///
111
/// Once a readiness event is received, the corresponding operation must be
112
/// performed repeatedly until it returns [`WouldBlock`]. Unless this is done,
113
/// there is no guarantee that another readiness event will be delivered, even
114
/// if further data is received for the event source.
115
///
116
/// [`WouldBlock`]: std::io::ErrorKind::WouldBlock
117
///
118
/// ### Readiness operations
119
///
120
/// The only readiness operations that are guaranteed to be present on all
121
/// supported platforms are [`readable`] and [`writable`]. All other readiness
122
/// operations may have false negatives and as such should be considered
123
/// **hints**. This means that if a socket is registered with [`readable`]
124
/// interest and either an error or close is received, a readiness event will
125
/// be generated for the socket, but it **may** only include `readable`
126
/// readiness. Also note that, given the potential for spurious events,
127
/// receiving a readiness event with `read_closed`, `write_closed`, or `error`
128
/// doesn't actually mean that a `read` on the socket will return a result
129
/// matching the readiness event.
130
///
131
/// In other words, portable programs that explicitly check for [`read_closed`],
132
/// [`write_closed`], or [`error`] readiness should be doing so as an
133
/// **optimization** and always be able to handle an error or close situation
134
/// when performing the actual read operation.
135
///
136
/// [`readable`]: ./event/struct.Event.html#method.is_readable
137
/// [`writable`]: ./event/struct.Event.html#method.is_writable
138
/// [`error`]: ./event/struct.Event.html#method.is_error
139
/// [`read_closed`]: ./event/struct.Event.html#method.is_read_closed
140
/// [`write_closed`]: ./event/struct.Event.html#method.is_write_closed
141
///
142
/// ### Registering handles
143
///
144
/// Unless otherwise noted, it should be assumed that types implementing
145
/// [`event::Source`] will never become ready unless they are registered with
146
/// `Poll`.
147
///
148
/// For example:
149
///
150
#[cfg_attr(all(feature = "os-poll", feature = "net"), doc = "```")]
151
#[cfg_attr(not(all(feature = "os-poll", feature = "net")), doc = "```ignore")]
152
/// # use std::error::Error;
153
/// # use std::net;
154
/// # fn main() -> Result<(), Box<dyn Error>> {
155
/// use mio::{Poll, Interest, Token};
156
/// use mio::net::TcpStream;
157
/// use std::net::SocketAddr;
158
/// use std::time::Duration;
159
/// use std::thread;
160
///
161
/// let address: SocketAddr = "127.0.0.1:0".parse()?;
162
/// let listener = net::TcpListener::bind(address)?;
163
/// let mut sock = TcpStream::connect(listener.local_addr()?)?;
164
///
165
/// thread::sleep(Duration::from_secs(1));
166
///
167
/// let poll = Poll::new()?;
168
///
169
/// // The connect is not guaranteed to have started until it is registered at
170
/// // this point
171
/// poll.registry().register(&mut sock, Token(0), Interest::READABLE | Interest::WRITABLE)?;
172
/// #     Ok(())
173
/// # }
174
/// ```
175
///
176
/// ### Dropping `Poll`
177
///
178
/// When the `Poll` instance is dropped it may cancel in-flight operations for
179
/// the registered [event sources], meaning that no further events for them may
180
/// be received. It also means operations on the registered event sources may no
181
/// longer work. It is up to the user to keep the `Poll` instance alive while
182
/// registered event sources are being used.
183
///
184
/// [event sources]: ./event/trait.Source.html
185
///
186
/// ### Accessing raw fd/socket/handle
187
///
188
/// Mio makes it possible for many types to be converted into a raw file
189
/// descriptor (fd, Unix), socket (Windows) or handle (Windows). This makes it
190
/// possible to support more operations on the type than Mio supports, for
191
/// example it makes [mio-aio] possible. However accessing the raw fd is not
192
/// without it's pitfalls.
193
///
194
/// Specifically performing I/O operations outside of Mio on these types (via
195
/// the raw fd) has unspecified behaviour. It could cause no more events to be
196
/// generated for the type even though it returned `WouldBlock` (in an operation
197
/// directly accessing the fd). The behaviour is OS specific and Mio can only
198
/// guarantee cross-platform behaviour if it can control the I/O.
199
///
200
/// [mio-aio]: https://github.com/asomers/mio-aio
201
///
202
/// *The following is **not** guaranteed, just a description of the current
203
/// situation!* Mio is allowed to change the following without it being considered
204
/// a breaking change, don't depend on this, it's just here to inform the user.
205
/// Currently the kqueue and epoll implementation support direct I/O operations
206
/// on the fd without Mio's knowledge. Windows however needs **all** I/O
207
/// operations to go through Mio otherwise it is not able to update it's
208
/// internal state properly and won't generate events.
209
///
210
/// ### Polling without registering event sources
211
///
212
///
213
/// *The following is **not** guaranteed, just a description of the current
214
/// situation!* Mio is allowed to change the following without it being
215
/// considered a breaking change, don't depend on this, it's just here to inform
216
/// the user. On platforms that use epoll, kqueue or IOCP (see implementation
217
/// notes below) polling without previously registering [event sources] will
218
/// result in sleeping forever, only a process signal will be able to wake up
219
/// the thread.
220
///
221
/// On WASM/WASI this is different as it doesn't support process signals,
222
/// furthermore the WASI specification doesn't specify a behaviour in this
223
/// situation, thus it's up to the implementation what to do here. As an
224
/// example, the wasmtime runtime will return `EINVAL` in this situation, but
225
/// different runtimes may return different results. If you have further
226
/// insights or thoughts about this situation (and/or how Mio should handle it)
227
/// please add you comment to [pull request#1580].
228
///
229
/// [event sources]: crate::event::Source
230
/// [pull request#1580]: https://github.com/tokio-rs/mio/pull/1580
231
///
232
/// # Implementation notes
233
///
234
/// `Poll` is backed by the selector provided by the operating system.
235
///
236
/// |      OS       |  Selector |
237
/// |---------------|-----------|
238
/// | Android       | [epoll]   |
239
/// | DragonFly BSD | [kqueue]  |
240
/// | FreeBSD       | [kqueue]  |
241
/// | iOS           | [kqueue]  |
242
/// | illumos       | [epoll]   |
243
/// | Linux         | [epoll]   |
244
/// | NetBSD        | [kqueue]  |
245
/// | OpenBSD       | [kqueue]  |
246
/// | Solaris       | [event ports] |
247
/// | Windows       | [IOCP]    |
248
/// | macOS         | [kqueue]  |
249
///
250
/// On all supported platforms, socket operations are handled by using the
251
/// system selector. Platform specific extensions (e.g. [`SourceFd`]) allow
252
/// accessing other features provided by individual system selectors. For
253
/// example, Linux's [`signalfd`] feature can be used by registering the FD with
254
/// `Poll` via [`SourceFd`].
255
///
256
/// On all platforms except windows, a call to [`Poll::poll`] is mostly just a
257
/// direct call to the system selector. However, [IOCP] uses a completion model
258
/// instead of a readiness model. In this case, `Poll` must adapt the completion
259
/// model Mio's API. While non-trivial, the bridge layer is still quite
260
/// efficient. The most expensive part being calls to `read` and `write` require
261
/// data to be copied into an intermediate buffer before it is passed to the
262
/// kernel.
263
///
264
/// [epoll]: https://man7.org/linux/man-pages/man7/epoll.7.html
265
/// [event ports]: https://docs.oracle.com/cd/E88353_01/html/E37843/port-create-3c.html
266
/// [kqueue]: https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2
267
/// [IOCP]: https://docs.microsoft.com/en-us/windows/win32/fileio/i-o-completion-ports
268
/// [`signalfd`]: https://man7.org/linux/man-pages/man2/signalfd.2.html
269
/// [`SourceFd`]: unix/struct.SourceFd.html
270
/// [`Poll::poll`]: struct.Poll.html#method.poll
271
pub struct Poll {
272
    registry: Registry,
273
}
274
275
/// Registers I/O resources.
276
pub struct Registry {
277
    selector: sys::Selector,
278
    /// Whether this selector currently has an associated waker.
279
    #[cfg(all(debug_assertions, not(any(target_os = "wasi", target_os = "horizon"))))]
280
    has_waker: Arc<AtomicBool>,
281
}
282
283
impl Poll {
284
    cfg_os_poll! {
285
        /// Return a new `Poll` handle.
286
        ///
287
        /// This function will make a syscall to the operating system to create
288
        /// the system selector. If this syscall fails, `Poll::new` will return
289
        /// with the error.
290
        ///
291
        /// close-on-exec flag is set on the file descriptors used by the selector to prevent
292
        /// leaking it to executed processes.
293
        ///
294
        /// See [struct] level docs for more details.
295
        ///
296
        /// [struct]: struct.Poll.html
297
        ///
298
        /// # Examples
299
        ///
300
        /// ```
301
        /// # use std::error::Error;
302
        /// # fn main() -> Result<(), Box<dyn Error>> {
303
        /// use mio::{Poll, Events};
304
        /// use std::time::Duration;
305
        ///
306
        /// let mut poll = match Poll::new() {
307
        ///     Ok(poll) => poll,
308
        ///     Err(e) => panic!("failed to create Poll instance; err={:?}", e),
309
        /// };
310
        ///
311
        /// // Create a structure to receive polled events
312
        /// let mut events = Events::with_capacity(1024);
313
        ///
314
        /// // Wait for events, but none will be received because no
315
        /// // `event::Source`s have been registered with this `Poll` instance.
316
        /// poll.poll(&mut events, Some(Duration::from_millis(500)))?;
317
        /// assert!(events.is_empty());
318
        /// #     Ok(())
319
        /// # }
320
        /// ```
321
17.3k
        pub fn new() -> io::Result<Poll> {
322
17.3k
            sys::Selector::new().map(|selector| Poll {
323
17.3k
                registry: Registry {
324
17.3k
                    selector,
325
17.3k
                    #[cfg(all(debug_assertions, not(any(target_os = "wasi", target_os = "horizon"))))]
326
17.3k
                    has_waker: Arc::new(AtomicBool::new(false)),
327
17.3k
                },
328
17.3k
            })
329
17.3k
        }
330
    }
331
332
    /// Returns a `Registry` which can be used to register
333
    /// `event::Source`s.
334
34.7k
    pub fn registry(&self) -> &Registry {
335
34.7k
        &self.registry
336
34.7k
    }
337
338
    /// Wait for readiness events
339
    ///
340
    /// Blocks the current thread and waits for readiness events for any of the
341
    /// [`event::Source`]s that have been registered with this `Poll` instance.
342
    /// The function will block until either at least one readiness event has
343
    /// been received or `timeout` has elapsed. A `timeout` of `None` means that
344
    /// `poll` will block until a readiness event has been received.
345
    ///
346
    /// The supplied `events` will be cleared and newly received readiness events
347
    /// will be pushed onto the end. At most `events.capacity()` events will be
348
    /// returned. If there are further pending readiness events, they will be
349
    /// returned on the next call to `poll`.
350
    ///
351
    /// A single call to `poll` may result in multiple readiness events being
352
    /// returned for a single event source. For example, if a TCP socket becomes
353
    /// both readable and writable, it may be possible for a single readiness
354
    /// event to be returned with both [`readable`] and [`writable`] readiness
355
    /// **OR** two separate events may be returned, one with [`readable`] set
356
    /// and one with [`writable`] set.
357
    ///
358
    /// Note that the `timeout` will be rounded up to the system clock
359
    /// granularity (usually 1ms), and kernel scheduling delays mean that
360
    /// the blocking interval may be overrun by a small amount. A timeout
361
    /// of [`Duration::ZERO`] is not affected by this rounding.
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
    /// # // WASI does not yet support multithreading:
391
    /// # if cfg!(target_os = "wasi") { return Ok(()) }
392
    /// use mio::{Events, Poll, Interest, Token};
393
    /// use mio::net::TcpStream;
394
    ///
395
    /// use std::net::{TcpListener, SocketAddr};
396
    /// use std::thread;
397
    ///
398
    /// // Bind a server socket to connect to.
399
    /// let addr: SocketAddr = "127.0.0.1:0".parse()?;
400
    /// let server = TcpListener::bind(addr)?;
401
    /// let addr = server.local_addr()?.clone();
402
    ///
403
    /// // Spawn a thread to accept the socket
404
    /// thread::spawn(move || {
405
    ///     let _ = server.accept();
406
    /// });
407
    ///
408
    /// // Construct a new `Poll` handle as well as the `Events` we'll store into
409
    /// let mut poll = Poll::new()?;
410
    /// let mut events = Events::with_capacity(1024);
411
    ///
412
    /// // Connect the stream
413
    /// let mut stream = TcpStream::connect(addr)?;
414
    ///
415
    /// // Register the stream with `Poll`
416
    /// poll.registry().register(
417
    ///     &mut stream,
418
    ///     Token(0),
419
    ///     Interest::READABLE | Interest::WRITABLE)?;
420
    ///
421
    /// // Wait for the socket to become ready. This has to happen in a loop to
422
    /// // handle spurious wakeups.
423
    /// loop {
424
    ///     poll.poll(&mut events, None)?;
425
    ///
426
    ///     for event in &events {
427
    ///         if event.token() == Token(0) && event.is_writable() {
428
    ///             // The socket connected (probably, it could still be a spurious
429
    ///             // wakeup)
430
    ///             return Ok(());
431
    ///         }
432
    ///     }
433
    /// }
434
    /// # }
435
    /// ```
436
    ///
437
    /// [struct]: #
438
21.9k
    pub fn poll(&mut self, events: &mut Events, timeout: Option<Duration>) -> io::Result<()> {
439
21.9k
        self.registry.selector.select(events.sys(), timeout)
440
21.9k
    }
441
}
442
443
#[cfg(all(
444
    unix,
445
    not(mio_unsupported_force_poll_poll),
446
    not(any(
447
        target_os = "aix",
448
        target_os = "espidf",
449
        target_os = "nuttx",
450
        target_os = "fuchsia",
451
        target_os = "haiku",
452
        target_os = "hermit",
453
        target_os = "hurd",
454
        target_os = "nto",
455
        target_os = "vita",
456
        target_os = "cygwin",
457
        target_os = "horizon"
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
17.3k
    pub fn register<S>(&self, source: &mut S, token: Token, interests: Interest) -> io::Result<()>
573
17.3k
    where
574
17.3k
        S: event::Source + ?Sized,
575
    {
576
17.3k
        trace!(
577
            "registering event source with poller: token={:?}, interests={:?}",
578
0
            token,
579
0
            interests
580
        );
581
17.3k
        source.register(self, token, interests)
582
17.3k
    }
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>
<mio::poll::Registry>::register::<mio::net::uds::stream::UnixStream>
Line
Count
Source
572
17.3k
    pub fn register<S>(&self, source: &mut S, token: Token, interests: Interest) -> io::Result<()>
573
17.3k
    where
574
17.3k
        S: event::Source + ?Sized,
575
    {
576
17.3k
        trace!(
577
            "registering event source with poller: token={:?}, interests={:?}",
578
0
            token,
579
0
            interests
580
        );
581
17.3k
        source.register(self, token, interests)
582
17.3k
    }
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
17.3k
    pub fn try_clone(&self) -> io::Result<Registry> {
716
17.3k
        self.selector.try_clone().map(|selector| Registry {
717
17.3k
            selector,
718
            #[cfg(all(debug_assertions, not(any(target_os = "wasi", target_os = "horizon"))))]
719
            has_waker: Arc::clone(&self.has_waker),
720
17.3k
        })
721
17.3k
    }
722
723
    /// Internal check to ensure only a single `Waker` is active per [`Poll`]
724
    /// instance.
725
    #[cfg(all(debug_assertions, not(any(target_os = "wasi", target_os = "horizon"))))]
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
    #[cfg_attr(target_os = "horizon", allow(dead_code))]
736
34.7k
    pub(crate) fn selector(&self) -> &sys::Selector {
737
34.7k
        &self.selector
738
34.7k
    }
739
}
740
741
impl fmt::Debug for Registry {
742
0
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
743
0
        fmt.debug_struct("Registry").finish()
744
0
    }
745
}
746
747
#[cfg(all(
748
    unix,
749
    not(mio_unsupported_force_poll_poll),
750
    not(any(
751
        target_os = "aix",
752
        target_os = "espidf",
753
        target_os = "nuttx",
754
        target_os = "haiku",
755
        target_os = "fuchsia",
756
        target_os = "hermit",
757
        target_os = "hurd",
758
        target_os = "nto",
759
        target_os = "vita",
760
        target_os = "cygwin",
761
        target_os = "horizon"
762
    )),
763
))]
764
impl AsFd for Registry {
765
0
    fn as_fd(&self) -> BorrowedFd<'_> {
766
0
        self.selector.as_fd()
767
0
    }
768
}
769
770
#[cfg(all(
771
    unix,
772
    not(mio_unsupported_force_poll_poll),
773
    not(any(
774
        target_os = "aix",
775
        target_os = "espidf",
776
        target_os = "nuttx",
777
        target_os = "haiku",
778
        target_os = "fuchsia",
779
        target_os = "hermit",
780
        target_os = "hurd",
781
        target_os = "nto",
782
        target_os = "vita",
783
        target_os = "cygwin",
784
        target_os = "horizon"
785
    )),
786
))]
787
impl AsRawFd for Registry {
788
0
    fn as_raw_fd(&self) -> RawFd {
789
0
        self.selector.as_raw_fd()
790
0
    }
791
}
792
793
cfg_os_poll! {
794
    #[cfg(all(
795
        unix,
796
        not(mio_unsupported_force_poll_poll),
797
        not(any(
798
            target_os = "aix",
799
            target_os = "espidf",
800
            target_os = "nuttx",
801
            target_os = "hermit",
802
            target_os = "hurd",
803
            target_os = "nto",
804
            target_os = "vita",
805
            target_os = "cygwin",
806
            target_os = "horizon"
807
        )),
808
    ))]
809
    #[test]
810
    pub fn as_raw_fd() {
811
        let poll = Poll::new().unwrap();
812
        assert!(poll.as_raw_fd() > 0);
813
    }
814
}