|
| 1 | +use {Result, Error, Errno, NixPath}; |
| 2 | +use errno; |
| 3 | +use libc::{self, DIR, c_long}; |
| 4 | + |
| 5 | +pub use self::fdopendir::*; |
| 6 | + |
| 7 | +pub struct Dir { |
| 8 | + handle: *mut DIR, |
| 9 | +} |
| 10 | + |
| 11 | +impl Drop for Dir { |
| 12 | + fn drop(&mut self) { |
| 13 | + unsafe { libc::closedir(self.handle) }; |
| 14 | + } |
| 15 | +} |
| 16 | + |
| 17 | +pub fn opendir<P: ?Sized + NixPath>(name: &P) -> Result<Dir> { |
| 18 | + let dirp = try!(name.with_nix_path(|cstr| unsafe { libc::opendir(cstr.as_ptr()) })); |
| 19 | + if dirp.is_null() { |
| 20 | + Err(Error::last().into()) |
| 21 | + } else { |
| 22 | + Ok(Dir { handle: dirp }) |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +#[cfg(not(any(target_os = "ios", target_os = "macos")))] |
| 27 | +mod fdopendir { |
| 28 | + use {Result, Error}; |
| 29 | + use dirent::Dir; |
| 30 | + use libc; |
| 31 | + use std::os::unix::io::RawFd; |
| 32 | + |
| 33 | + pub fn fdopendir(fd: RawFd) -> Result<Dir> { |
| 34 | + let dirp = unsafe { libc::fdopendir(fd) }; |
| 35 | + if dirp.is_null() { |
| 36 | + Err(Error::last().into()) |
| 37 | + } else { |
| 38 | + Ok(Dir { handle: dirp }) |
| 39 | + } |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +pub fn readdir<'a>(dir: &'a mut Dir) -> Result<Option<&'a libc::dirent>> { |
| 44 | + let dirent = unsafe { |
| 45 | + Errno::clear(); |
| 46 | + libc::readdir(dir.handle) |
| 47 | + }; |
| 48 | + if dirent.is_null() { |
| 49 | + match Errno::last() { |
| 50 | + errno::UnknownErrno => Ok(None), |
| 51 | + _ => Err(Error::last().into()), |
| 52 | + } |
| 53 | + } else { |
| 54 | + Ok(Some(unsafe { &*dirent })) |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +pub fn seekdir<'a>(dir: &'a mut Dir, loc: c_long) { |
| 59 | + unsafe { libc::seekdir(dir.handle, loc) }; |
| 60 | +} |
| 61 | + |
| 62 | +pub fn telldir<'a>(dir: &'a mut Dir) -> c_long { |
| 63 | + unsafe { libc::telldir(dir.handle) } |
| 64 | +} |
0 commit comments