listener/
listener.rs

1use io_uring_epoll::{EpollHandler, HandledFd};
2use std::net::{IpAddr, Ipv4Addr, SocketAddr};
3use std::os::fd::AsRawFd;
4
5fn main() {
6    // The 10 denotes power of two capacity to io_uring::IoUring
7    let mut handler = EpollHandler::new(10).expect("Unable to create EPoll Handler");
8
9    // This works with any impl that provides std::os::fd::AsRawFd impl
10    // In POSIX/UNIX-like it's just i32 file number or "fileno"
11    let listen =
12        std::net::TcpListener::bind(SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 0))
13            .unwrap();
14
15    // Add the listen handle into EpollHandler
16    let mut handle_fd = HandledFd::new(listen.as_raw_fd());
17    let set_mask = handle_fd.set_in(true);
18    assert_eq!(set_mask, 1);
19    handler.add_fd(&handle_fd).unwrap();
20
21    // Prepare a commit all changes into io_uring::SubmissionQueue
22    let handle_status = handler.prepare_submit().unwrap();
23    assert_eq!(handle_status.count_new(), 1);
24    assert_eq!(handle_status.count_changes(), 0);
25    assert_eq!(handle_status.count_empty(), 0);
26    assert_eq!(handle_status.errors().len(), 0);
27
28    // Take temp ref to io_uring::SubmissionQeueue
29    let submission = handler.io_uring().submission();
30    assert_eq!(submission.len(), 1);
31    assert_eq!(submission.is_empty(), false);
32    assert_eq!(submission.dropped(), 0);
33    assert_eq!(submission.cq_overflow(), false);
34    assert_eq!(submission.is_full(), false);
35    drop(submission);
36
37    // async version is with submit()
38    handler.submit_and_wait(1).unwrap();
39
40    // Ensure that the kernel ate it
41    let submission = handler.io_uring().submission();
42    assert_eq!(submission.len(), 0);
43    assert_eq!(submission.is_empty(), true);
44    assert_eq!(submission.dropped(), 0);
45    assert_eq!(submission.cq_overflow(), false);
46    assert_eq!(submission.is_full(), false);
47    drop(submission);
48
49    let c_queue = handler.io_uring().completion();
50    let mut c_attempts = 0;
51    loop {
52        if c_queue.is_empty() == false {
53            assert_eq!(c_queue.len(), 1);
54            break;
55        }
56        if c_attempts == 10 {
57            panic!("Took more than 100 ms - completion never finished?");
58        }
59        std::thread::sleep(std::time::Duration::from_millis(10));
60        c_attempts += 1;
61    }
62}