|
| 1 | +use rustix::fd::{AsFd, AsRawFd, FromRawFd, IntoRawFd, OwnedFd}; |
| 2 | +use rustix::io::{pipe, poll, read, with_retrying, write, PollFd, PollFlags}; |
| 3 | + |
| 4 | +#[test] |
| 5 | +fn test_poll() { |
| 6 | + // Create a pipe. |
| 7 | + let (reader, writer) = pipe().unwrap(); |
| 8 | + let mut poll_fds = [PollFd::new(&reader, PollFlags::IN)]; |
| 9 | + assert_eq!(poll_fds[0].as_fd().as_raw_fd(), reader.as_fd().as_raw_fd()); |
| 10 | + |
| 11 | + // `poll` should say there's nothing ready to be read fron the pipe. |
| 12 | + let num = with_retrying(|| poll(&mut poll_fds, 0)).unwrap(); |
| 13 | + assert_eq!(num, 0); |
| 14 | + assert!(poll_fds[0].revents().is_empty()); |
| 15 | + assert_eq!(poll_fds[0].as_fd().as_raw_fd(), reader.as_fd().as_raw_fd()); |
| 16 | + |
| 17 | + // Write a byte to the pipe. |
| 18 | + assert_eq!(with_retrying(|| write(&writer, b"a")).unwrap(), 1); |
| 19 | + |
| 20 | + // `poll` should now say there's data to be read. |
| 21 | + let num = with_retrying(|| poll(&mut poll_fds, -1)).unwrap(); |
| 22 | + assert_eq!(num, 1); |
| 23 | + assert_eq!(poll_fds[0].revents(), PollFlags::IN); |
| 24 | + assert_eq!(poll_fds[0].as_fd().as_raw_fd(), reader.as_fd().as_raw_fd()); |
| 25 | + |
| 26 | + // Read the byte from the pipe. |
| 27 | + let mut buf = [b'\0']; |
| 28 | + assert_eq!(with_retrying(|| read(&reader, &mut buf)).unwrap(), 1); |
| 29 | + assert_eq!(buf[0], b'a'); |
| 30 | + assert_eq!(poll_fds[0].as_fd().as_raw_fd(), reader.as_fd().as_raw_fd()); |
| 31 | + |
| 32 | + // Poll should now say there's no more data to be read. |
| 33 | + let num = with_retrying(|| poll(&mut poll_fds, 0)).unwrap(); |
| 34 | + assert_eq!(num, 0); |
| 35 | + assert!(poll_fds[0].revents().is_empty()); |
| 36 | + assert_eq!(poll_fds[0].as_fd().as_raw_fd(), reader.as_fd().as_raw_fd()); |
| 37 | +} |
| 38 | + |
| 39 | +#[test] |
| 40 | +fn test_poll_fd_set_fd() { |
| 41 | + // Make up some file descriptors so that we can test that set_fd works. |
| 42 | + let a = unsafe { OwnedFd::from_raw_fd(777) }; |
| 43 | + let mut poll_fd = PollFd::new(&a, PollFlags::empty()); |
| 44 | + assert_eq!(poll_fd.as_fd().as_raw_fd(), 777); |
| 45 | + |
| 46 | + let b = unsafe { OwnedFd::from_raw_fd(888) }; |
| 47 | + poll_fd.set_fd(&b); |
| 48 | + assert_eq!(poll_fd.as_fd().as_raw_fd(), 888); |
| 49 | + |
| 50 | + // Don't attempt to close our made-up file descriptors. |
| 51 | + let _ = a.into_raw_fd(); |
| 52 | + let _ = b.into_raw_fd(); |
| 53 | +} |
0 commit comments