Skip to content

Commit ff41615

Browse files
committed
Relax lifetime requirements for PollFd::new
Fixes #2118
1 parent 154a8a4 commit ff41615

File tree

2 files changed

+31
-8
lines changed

2 files changed

+31
-8
lines changed

CHANGELOG.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,13 @@
33
All notable changes to this project will be documented in this file.
44
This project adheres to [Semantic Versioning](https://semver.org/).
55

6+
## [Unreleased] - ReleaseDate
7+
8+
### Fixed
9+
10+
- Relaxed lifetime requirements for `PollFd::new`.
11+
([#2134](https://github.com/nix-rust/nix/pull/2134))
12+
613
## [0.27.1] - 2023-08-28
714

815
### Fixed

src/poll.rs

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,21 +22,37 @@ pub struct PollFd<'fd> {
2222
impl<'fd> PollFd<'fd> {
2323
/// Creates a new `PollFd` specifying the events of interest
2424
/// for a given file descriptor.
25-
//
25+
///
26+
/// # Examples
27+
/// ```no_run
28+
/// # use std::os::fd::{AsFd, AsRawFd, FromRawFd, OwnedFd};
29+
/// # use nix::{
30+
/// # poll::{PollFd, PollFlags, poll},
31+
/// # unistd::{pipe, read}
32+
/// # };
33+
/// let (r, w) = pipe().unwrap();
34+
/// let r = unsafe { OwnedFd::from_raw_fd(r) };
35+
/// let pfd = PollFd::new(&r.as_fd(), PollFlags::POLLIN);
36+
/// let mut fds = [pfd];
37+
/// poll(&mut fds, -1).unwrap();
38+
/// let mut buf = [0u8; 80];
39+
/// read(r.as_raw_fd(), &mut buf[..]);
40+
/// ```
41+
// Unlike I/O functions, constructors like this must take `AsFd` by
42+
// reference. Otherwise, an `OwnedFd` argument would be dropped at the end
43+
// of the method, leaving the structure referencing a closed file
44+
// descriptor.
2645
// Different from other I/O-safe interfaces, here, we have to take `AsFd`
2746
// by reference to prevent the case where the `fd` is closed but it is
2847
// still in use. For example:
2948
//
3049
// ```rust
31-
// let (reader, _) = pipe().unwrap();
32-
//
33-
// // If `PollFd::new()` takes `AsFd` by value, then `reader` will be consumed,
34-
// // but the file descriptor of `reader` will still be in use.
35-
// let pollfd = PollFd::new(reader, flag);
36-
//
50+
// let (r, _) = pipe().unwrap();
51+
// let reader: OwnedFd = unsafe { OwnedFd::from_raw_fd(r) };
52+
// let pollfd = PollFd::new(reader, flag); // Drops the OwnedFd
3753
// // Do something with `pollfd`, which uses the CLOSED fd.
3854
// ```
39-
pub fn new<Fd: AsFd>(fd: &'fd Fd, events: PollFlags) -> PollFd<'fd> {
55+
pub fn new<Fd: AsFd + 'fd>(fd: &Fd, events: PollFlags) -> PollFd<'fd> {
4056
PollFd {
4157
pollfd: libc::pollfd {
4258
fd: fd.as_fd().as_raw_fd(),

0 commit comments

Comments
 (0)