11//! Portably monitor a group of file descriptors for readiness.
2+ use std:: convert:: TryFrom ;
23use std:: iter:: FusedIterator ;
34use std:: mem;
45use std:: ops:: Range ;
@@ -17,6 +18,13 @@ pub use libc::FD_SETSIZE;
1718#[ derive( Clone , Copy , Debug , Eq , Hash , PartialEq ) ]
1819pub struct FdSet ( libc:: fd_set ) ;
1920
21+ fn assert_fd_valid ( fd : RawFd ) {
22+ assert ! (
23+ usize :: try_from( fd) . map_or( false , |fd| fd < FD_SETSIZE ) ,
24+ "fd must be in the range 0..FD_SETSIZE" ,
25+ ) ;
26+ }
27+
2028impl FdSet {
2129 /// Create an empty `FdSet`
2230 pub fn new ( ) -> FdSet {
@@ -29,16 +37,19 @@ impl FdSet {
2937
3038 /// Add a file descriptor to an `FdSet`
3139 pub fn insert ( & mut self , fd : RawFd ) {
40+ assert_fd_valid ( fd) ;
3241 unsafe { libc:: FD_SET ( fd, & mut self . 0 ) } ;
3342 }
3443
3544 /// Remove a file descriptor from an `FdSet`
3645 pub fn remove ( & mut self , fd : RawFd ) {
46+ assert_fd_valid ( fd) ;
3747 unsafe { libc:: FD_CLR ( fd, & mut self . 0 ) } ;
3848 }
3949
4050 /// Test an `FdSet` for the presence of a certain file descriptor.
4151 pub fn contains ( & self , fd : RawFd ) -> bool {
52+ assert_fd_valid ( fd) ;
4253 unsafe { libc:: FD_ISSET ( fd, & self . 0 ) }
4354 }
4455
0 commit comments