os/uapi/
select.rs

1//! select() system call definitions
2
3use core::mem;
4
5/// Maximum number of file descriptors in fd_set
6pub const FD_SETSIZE: usize = 1024;
7
8/// Number of longs needed to hold FD_SETSIZE bits
9const NFDBITS: usize = 8 * mem::size_of::<usize>();
10const FD_SET_LONGS: usize = (FD_SETSIZE + NFDBITS - 1) / NFDBITS;
11
12/// File descriptor set for select()
13#[repr(C)]
14#[derive(Clone, Copy)]
15pub struct FdSet {
16    fds_bits: [usize; FD_SET_LONGS],
17}
18
19impl FdSet {
20    /// Create a new empty fd_set
21    pub fn new() -> Self {
22        Self {
23            fds_bits: [0; FD_SET_LONGS],
24        }
25    }
26
27    /// Clear all bits (FD_ZERO)
28    pub fn zero(&mut self) {
29        self.fds_bits = [0; FD_SET_LONGS];
30    }
31
32    /// Set a bit (FD_SET)
33    pub fn set(&mut self, fd: usize) {
34        if fd < FD_SETSIZE {
35            self.fds_bits[fd / NFDBITS] |= 1 << (fd % NFDBITS);
36        }
37    }
38
39    /// Clear a bit (FD_CLR)
40    pub fn clear(&mut self, fd: usize) {
41        if fd < FD_SETSIZE {
42            self.fds_bits[fd / NFDBITS] &= !(1 << (fd % NFDBITS));
43        }
44    }
45
46    /// Test a bit (FD_ISSET)
47    pub fn is_set(&self, fd: usize) -> bool {
48        if fd < FD_SETSIZE {
49            (self.fds_bits[fd / NFDBITS] & (1 << (fd % NFDBITS))) != 0
50        } else {
51            false
52        }
53    }
54}