Skip to content

Commit 2a75d70

Browse files
committed
add support for dirent family
1 parent d0628e1 commit 2a75d70

File tree

5 files changed

+185
-0
lines changed

5 files changed

+185
-0
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ This project adheres to [Semantic Versioning](http://semver.org/).
2121
- Added `nix::ptrace::{ptrace_get_data, ptrace_getsiginfo, ptrace_setsiginfo
2222
and nix::Error::UnsupportedOperation}`
2323
([#614](https://github.com/nix-rust/nix/pull/614))
24+
- Added `nix::dirent::{opendir, fdopendir, readdir, telldir, seekdir}`
25+
([#558](https://github.com/nix-rust/nix/pull/558))
2426

2527
### Changed
2628
- Changed ioctl! write to take argument by value instead as pointer.

src/dirent.rs

Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
//! Directory Stream functions
2+
//!
3+
//! [Further reading and details on the C API](http://man7.org/linux/man-pages/man3/opendir.3.html)
4+
5+
use {Result, Error, Errno, NixPath};
6+
use errno;
7+
use libc::{self, DIR, c_long};
8+
use std::convert::{AsRef, Into};
9+
use std::ffi::CStr;
10+
use std::mem;
11+
12+
#[cfg(any(target_os = "linux", target_os = "android"))]
13+
use libc::{dirent64, ino64_t, readdir64};
14+
15+
#[cfg(not(any(target_os = "linux", target_os = "android")))]
16+
use libc::{dirent as dirent64, ino_t as ino64_t, readir as readdir64};
17+
18+
#[cfg(not(any(target_os = "ios", target_os = "macos")))]
19+
use std::os::unix::io::RawFd;
20+
21+
/// Directory Stream object
22+
pub struct DirectoryStream(*mut DIR);
23+
24+
impl AsRef<DIR> for DirectoryStream {
25+
fn as_ref(&self) -> &DIR {
26+
unsafe { &*self.0 }
27+
}
28+
}
29+
30+
/// Consumes directory stream and return underlying directory pointer.
31+
///
32+
/// The pointer must be deallocated manually using `libc::closedir`
33+
impl Into<*mut DIR> for DirectoryStream {
34+
fn into(self) -> *mut DIR {
35+
let dirp = self.0;
36+
mem::forget(self);
37+
dirp
38+
}
39+
}
40+
41+
impl Drop for DirectoryStream {
42+
fn drop(&mut self) {
43+
unsafe { libc::closedir(self.0) };
44+
}
45+
}
46+
47+
/// A directory entry
48+
pub struct DirectoryEntry<'a>(&'a dirent64);
49+
50+
impl<'a> DirectoryEntry<'a> {
51+
/// File name
52+
pub fn name(&self) -> &CStr {
53+
unsafe{
54+
CStr::from_ptr(self.0.d_name.as_ptr())
55+
}
56+
}
57+
58+
/// Inode number
59+
pub fn inode(&self) -> ino64_t {
60+
#[cfg(not(any(target_os = "freebsd", target_os = "netbsd", target_os="dragonfly")))]
61+
return self.0.d_ino;
62+
#[cfg(any(target_os = "freebsd", target_os = "netbsd", target_os="dragonfly"))]
63+
return self.0.d_fileno;
64+
}
65+
}
66+
67+
impl<'a> AsRef<dirent64> for DirectoryEntry<'a> {
68+
fn as_ref(&self) -> &dirent64 {
69+
self.0
70+
}
71+
}
72+
73+
/// Opens a directory stream corresponding to the directory name.
74+
///
75+
/// The stream is positioned at the first entry in the directory.
76+
pub fn opendir<P: ?Sized + NixPath>(name: &P) -> Result<DirectoryStream> {
77+
let dirp = try!(name.with_nix_path(|cstr| unsafe { libc::opendir(cstr.as_ptr()) }));
78+
if dirp.is_null() {
79+
Err(Error::last().into())
80+
} else {
81+
Ok(DirectoryStream(dirp))
82+
}
83+
}
84+
85+
/// Like `opendir()`, but returns a directory stream for the directory
86+
/// referred to by the open file descriptor `fd`.
87+
///
88+
/// After a successful call to this function, `fd` is used internally by
89+
/// the implementation, and should not otherwise be used by the application
90+
#[cfg(not(any(target_os = "ios", target_os = "macos")))]
91+
pub fn fdopendir(fd: RawFd) -> Result<DirectoryStream> {
92+
let dirp = unsafe { libc::fdopendir(fd) };
93+
if dirp.is_null() {
94+
Err(Error::last().into())
95+
} else {
96+
Ok(DirectoryStream(dirp))
97+
}
98+
}
99+
100+
/// Returns the next directory entry in the directory stream.
101+
///
102+
/// It returns `Some(None)` on reaching the end of the directory stream.
103+
pub fn readdir<'a>(dir: &'a mut DirectoryStream) -> Result<Option<DirectoryEntry>> {
104+
let dirent = unsafe {
105+
Errno::clear();
106+
readdir64(dir.0)
107+
};
108+
if dirent.is_null() {
109+
match Errno::last() {
110+
errno::UnknownErrno => Ok(None),
111+
_ => Err(Error::last().into()),
112+
}
113+
} else {
114+
Ok(Some(DirectoryEntry(unsafe { &*dirent })))
115+
}
116+
}
117+
118+
/// Sets the location in the directory stream from which the next `readdir` call will start.
119+
///
120+
/// The `loc` argument should be a value returned by a previous call to `telldir`
121+
#[cfg(not(any(target_os = "android")))]
122+
pub fn seekdir<'a>(dir: &'a mut DirectoryStream, loc: c_long) {
123+
unsafe { libc::seekdir(dir.0, loc) };
124+
}
125+
126+
/// Returns the current location associated with the directory stream.
127+
#[cfg(not(any(target_os = "android")))]
128+
pub fn telldir<'a>(dir: &'a mut DirectoryStream) -> c_long {
129+
unsafe { libc::telldir(dir.0) }
130+
}

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ pub mod libc {
3434
pub use libc::{c_int, c_void};
3535
pub use errno::Errno;
3636

37+
pub mod dirent;
3738
pub mod errno;
3839
pub mod features;
3940
pub mod fcntl;

test/test.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ extern crate tempfile;
1010
extern crate nix_test as nixtest;
1111

1212
mod sys;
13+
mod test_dirent;
1314
mod test_fcntl;
1415
#[cfg(any(target_os = "linux"))]
1516
mod test_mq;

test/test_dirent.rs

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
use nix::dirent::{self, opendir, readdir, seekdir, telldir, DirectoryStream};
2+
use std::path::Path;
3+
use tempdir::TempDir;
4+
5+
fn test_readdir<Open>(open_fn: Open)
6+
where Open: Fn(&Path) -> DirectoryStream
7+
{
8+
let tempdir = TempDir::new("nix-test_readdir")
9+
.unwrap_or_else(|e| panic!("tempdir failed: {}", e));
10+
let mut dir = open_fn(tempdir.path());
11+
let letter1 = readdir(&mut dir)
12+
.unwrap()
13+
.unwrap()
14+
.name()
15+
.to_bytes()[0];
16+
assert_eq!(letter1, '.' as u8);
17+
18+
let pos = telldir(&mut dir);
19+
20+
let letter2 = readdir(&mut dir)
21+
.unwrap()
22+
.unwrap()
23+
.name()
24+
.to_bytes()[0];
25+
assert_eq!(letter2, '.' as u8);
26+
27+
seekdir(&mut dir, pos); // same again
28+
29+
let letter3 = readdir(&mut dir)
30+
.unwrap()
31+
.unwrap()
32+
.name()
33+
.to_bytes()[0];
34+
assert_eq!(letter3, '.' as u8);
35+
36+
// end of directory
37+
assert!(readdir(&mut dir).unwrap().is_none());
38+
}
39+
40+
#[test]
41+
fn test_opendir() {
42+
test_readdir(|path| opendir(path).unwrap());
43+
}
44+
45+
#[cfg(not(any(target_os = "ios", target_os = "macos")))]
46+
#[test]
47+
fn test_fdopendir() {
48+
use std::os::unix::io::IntoRawFd;
49+
use std::fs::File;
50+
test_readdir(|path| dirent::fdopendir(File::open(path).unwrap().into_raw_fd()).unwrap());
51+
}

0 commit comments

Comments
 (0)