Skip to content

Commit e4660c1

Browse files
authored
Merge pull request #19 from ksqsf/master
Add methods to query the directory itself
2 parents a46c127 + 0461377 commit e4660c1

File tree

2 files changed

+31
-8
lines changed

2 files changed

+31
-8
lines changed

src/dir.rs

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use std::path::{PathBuf};
88

99
use libc;
1010
use metadata::{self, Metadata};
11-
use list::{DirIter, open_dir};
11+
use list::{DirIter, open_dir, open_dirfd};
1212

1313
use {Dir, AsPath};
1414

@@ -50,11 +50,18 @@ impl Dir {
5050

5151
/// List subdirectory of this dir
5252
///
53-
/// You can list directory itself if `"."` is specified as path.
53+
/// You can list directory itself with `list_self`.
5454
pub fn list_dir<P: AsPath>(&self, path: P) -> io::Result<DirIter> {
5555
open_dir(self, to_cstr(path)?.as_ref())
5656
}
5757

58+
/// List this dir
59+
pub fn list_self(&self) -> io::Result<DirIter> {
60+
unsafe {
61+
open_dirfd(libc::dup(self.0))
62+
}
63+
}
64+
5865
/// Open subdirectory
5966
pub fn sub_dir<P: AsPath>(&self, path: P) -> io::Result<Dir> {
6067
self._sub_dir(to_cstr(path)?.as_ref())
@@ -378,6 +385,18 @@ impl Dir {
378385
}
379386
}
380387

388+
/// Returns the metadata of the directory itself.
389+
pub fn self_metadata(&self) -> io::Result<Metadata> {
390+
unsafe {
391+
let mut stat = mem::zeroed();
392+
let res = libc::fstat(self.0, &mut stat);
393+
if res < 0 {
394+
Err(io::Error::last_os_error())
395+
} else {
396+
Ok(metadata::new(stat))
397+
}
398+
}
399+
}
381400
}
382401

383402
/// Rename (move) a file between directories

src/list.rs

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -66,19 +66,23 @@ impl DirIter {
6666
}
6767
}
6868

69+
pub fn open_dirfd(fd: libc::c_int) -> io::Result<DirIter> {
70+
let dir = unsafe { libc::fdopendir(fd) };
71+
if dir == std::ptr::null_mut() {
72+
Err(io::Error::last_os_error())
73+
} else {
74+
Ok(DirIter { dir: dir })
75+
}
76+
}
77+
6978
pub fn open_dir(dir: &Dir, path: &CStr) -> io::Result<DirIter> {
7079
let dir_fd = unsafe {
7180
libc::openat(dir.0, path.as_ptr(), libc::O_DIRECTORY|libc::O_CLOEXEC)
7281
};
7382
if dir_fd < 0 {
7483
Err(io::Error::last_os_error())
7584
} else {
76-
let dir = unsafe { libc::fdopendir(dir_fd) };
77-
if dir == ptr::null_mut() {
78-
Err(io::Error::last_os_error())
79-
} else {
80-
Ok(DirIter { dir: dir })
81-
}
85+
open_dirfd(dir_fd)
8286
}
8387
}
8488

0 commit comments

Comments
 (0)