Coverage Report

Created: 2026-02-14 06:16

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