devashishdxt / mock-io

Mock IO listener and stream for Rust
Other
7 stars 3 forks source link

Feature: set_nonblocking on MockStream #2

Open pczarn opened 2 years ago

pczarn commented 2 years ago

Hey, thanks for this piece of software!

@devashishdxt would you be open to adding an option for nonblocking access? This option would move a stream into or out of nonblocking mode, similar to std's TcpStream::set_nonblocking.

devashishdxt commented 2 years ago

Thanks for creating this issue. I think i'll be good to add this API. But, I'm not sure how you intend to use it?

pczarn commented 2 years ago

@devashishdxt It would be implemented with try_recv and allow the caller e.g. to enforce their own timeout. On a second thought, I would also implement set_read_timeout and set_write_timeout. This is for ensuring the test does not hang indefinitely if the other side of the stream does not write anything.

For example:

let mut all_buf = vec![];
let timeout = Duration::from_secs(3);
let instant = Instant::now();
while all_buf.len() < expected.len() {
    let mut buf = vec![0u8; 512];
    let size = stream.read(&mut buf).expect("reading from mock failed"); // make this nonblocking?
    all_buf.extend(buf[0..size].iter().cloned());
    assert!(instant.elapsed() < timeout, "timed out, expected read: {}", std::str::from_utf8(expected).unwrap());
}
let actual = &all_buf[..];
assert_eq!(actual, expected);
pczarn commented 2 years ago

I added a Work In Progress PR for you to look into proposed changes.