Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/2383.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added implementations of `FromIterator` and `From` for `FdSet`, allowing them to be constructed from iterables of types that implement `AsFd`.
20 changes: 19 additions & 1 deletion src/sys/select.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::convert::TryFrom;
use std::iter::FusedIterator;
use std::mem;
use std::ops::Range;
use std::os::unix::io::{AsRawFd, BorrowedFd, RawFd};
use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd};
use std::ptr::{null, null_mut};

pub use libc::FD_SETSIZE;
Expand Down Expand Up @@ -163,6 +163,24 @@ impl<'a, 'fd> DoubleEndedIterator for Fds<'a, 'fd> {

impl<'a, 'fd> FusedIterator for Fds<'a, 'fd> {}

impl<'fd, F> FromIterator<F> for FdSet<'fd> where F: 'fd + AsFd {
fn from_iter<T>(iter: T) -> Self where T: IntoIterator<Item = F> {
let mut result = FdSet::new();
for fd in iter.into_iter() {
let fd = fd.as_fd();
assert_fd_valid(fd.as_raw_fd());
unsafe { libc::FD_SET(fd.as_raw_fd(), &mut result.set) };
}
result
}
}

impl<'fd, T, F> From<T> for FdSet<'fd> where T: IntoIterator<Item = F>, F: 'fd + AsFd {
fn from(value: T) -> Self {
value.into_iter().collect()
}
}

/// Monitors file descriptors for readiness
///
/// Returns the total number of ready file descriptors in all sets. The sets are changed so that all
Expand Down
27 changes: 27 additions & 0 deletions test/sys/test_select.rs
Original file line number Diff line number Diff line change
Expand Up @@ -291,3 +291,30 @@ fn test_select_nfds2() {
assert!(fd_set.contains(r1.as_fd()));
assert!(!fd_set.contains(r2.as_fd()));
}

#[test]
fn test_fdset_from_iterable() {
let (r1, w1) = pipe().unwrap();
let (r2, w2) = pipe().unwrap();
let reads = [r1, r2]
.into_iter()
.map(|fd| (fd.as_raw_fd(), fd))
.collect::<std::collections::HashMap<_, _>>();
let writes = [w1, w2];
let reads_fdset: FdSet = reads.values().into();
let writes_fdset: FdSet = writes.iter().into();
assert_eq!(
reads_fdset
.fds(None)
.map(|fd| fd.as_raw_fd())
.collect::<std::collections::HashSet<_>>(),
reads.values().map(|fd| fd.as_raw_fd()).collect()
);
assert_eq!(
writes_fdset
.fds(None)
.map(|fd| fd.as_raw_fd())
.collect::<std::collections::HashSet<_>>(),
writes.iter().map(|fd| fd.as_raw_fd()).collect()
);
}