Skip to content
This repository has been archived by the owner on Jun 26, 2022. It is now read-only.

Commit

Permalink
Add File::get_nonblocking
Browse files Browse the repository at this point in the history
Fixes #7.
  • Loading branch information
Rufflewind committed Jan 28, 2018
1 parent 36b0542 commit 916fe24
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "tokio-file-unix"
version = "0.4.1"
version = "0.4.2"
authors = ["Phil Ruffwind <rf@rufflewind.com>"]
description = "Asynchronous support for epollable files via Tokio on Unix-like platforms"
documentation = "https://docs.rs/tokio-file-unix"
Expand Down
4 changes: 4 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## 0.4.2

- Add `File::get_nonblocking`.

## 0.4.1

- Improved documentation and added another example `stdin_lines.rs`.
Expand Down
44 changes: 44 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,19 @@ impl<F: AsRawFd> File<F> {
Ok(file)
}

/// Gets the nonblocking mode of the underlying file descriptor.
///
/// Implementation detail: uses `fcntl` to retrieve `O_NONBLOCK`.
pub fn get_nonblocking(&self) -> io::Result<bool> {
unsafe {
let flags = libc::fcntl(self.as_raw_fd(), libc::F_GETFL);
if flags < 0 {
return Err(io::Error::last_os_error());
}
Ok(flags & libc::O_NONBLOCK != 0)
}
}

/// Sets the nonblocking mode of the underlying file descriptor to either
/// on (`true`) or off (`false`). If `File::new_nb` was previously used
/// to construct the `File`, then nonblocking mode has already been turned
Expand Down Expand Up @@ -412,3 +425,34 @@ impl From<Newline> for u8 {
b'\n'
}
}

#[cfg(test)]
mod tests {
use super::*;
use std::os::unix::io::{AsRawFd, RawFd};
use std::os::unix::net::UnixStream;

pub struct RefAsRawFd<T>(pub T);
impl<'a, T: AsRawFd> AsRawFd for RefAsRawFd<&'a T> {
fn as_raw_fd(&self) -> RawFd { self.0.as_raw_fd() }
}

#[test]
fn test_nonblocking() {
let (sock, _) = UnixStream::pair().unwrap();
{
let file = File::new_nb(RefAsRawFd(&sock)).unwrap();
assert!(file.get_nonblocking().unwrap());
file.set_nonblocking(false).unwrap();
assert!(!file.get_nonblocking().unwrap());
file.set_nonblocking(true).unwrap();
assert!(file.get_nonblocking().unwrap());
file.set_nonblocking(false).unwrap();
assert!(!file.get_nonblocking().unwrap());
}
{
let file = File::raw_new(RefAsRawFd(&sock));
assert!(!file.get_nonblocking().unwrap());
}
}
}

0 comments on commit 916fe24

Please sign in to comment.