Solution

  1. mod ffi {
  2.     use std::os::raw::{c_char, c_int};
  3.     #[cfg(not(target_os = "macos"))]
  4.     use std::os::raw::{c_long, c_uchar, c_ulong, c_ushort};
  5.     // Opaque type. See https://doc.rust-lang.org/nomicon/ffi.html.
  6.     #[repr(C)]
  7.     pub struct DIR {
  8.         _data: [u8; 0],
  9.         _marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>,
  10.     }
  11.     // Layout according to the Linux man page for readdir(3), where ino_t and
  12.     // off_t are resolved according to the definitions in
  13.     // /usr/include/x86_64-linux-gnu/{sys/types.h, bits/typesizes.h}.
  14.     #[cfg(not(target_os = "macos"))]
  15.     #[repr(C)]
  16.     pub struct dirent {
  17.         pub d_ino: c_ulong,
  18.         pub d_off: c_long,
  19.         pub d_reclen: c_ushort,
  20.         pub d_type: c_uchar,
  21.         pub d_name: [c_char; 256],
  22.     }
  23.     // Layout according to the macOS man page for dir(5).
  24.     #[cfg(all(target_os = "macos"))]
  25.     #[repr(C)]
  26.     pub struct dirent {
  27.         pub d_fileno: u64,
  28.         pub d_seekoff: u64,
  29.         pub d_reclen: u16,
  30.         pub d_namlen: u16,
  31.         pub d_type: u8,
  32.         pub d_name: [c_char; 1024],
  33.     }
  34.     unsafe extern "C" {
  35.         pub unsafe fn opendir(s: *const c_char) -> *mut DIR;
  36.         #[cfg(not(all(target_os = "macos", target_arch = "x86_64")))]
  37.         pub unsafe fn readdir(s: *mut DIR) -> *const dirent;
  38.         // See https://github.com/rust-lang/libc/issues/414 and the section on
  39.         // _DARWIN_FEATURE_64_BIT_INODE in the macOS man page for stat(2).
  40.         //
  41.         // "Platforms that existed before these updates were available" refers
  42.         // to macOS (as opposed to iOS / wearOS / etc.) on Intel and PowerPC.
  43.         #[cfg(all(target_os = "macos", target_arch = "x86_64"))]
  44.         #[link_name = "readdir$INODE64"]
  45.         pub unsafe fn readdir(s: *mut DIR) -> *const dirent;
  46.         pub unsafe fn closedir(s: *mut DIR) -> c_int;
  47.     }
  48. }
  49. use std::ffi::{CStr, CString, OsStr, OsString};
  50. use std::os::unix::ffi::OsStrExt;
  51. #[derive(Debug)]
  52. struct DirectoryIterator {
  53.     path: CString,
  54.     dir: *mut ffi::DIR,
  55. }
  56. impl DirectoryIterator {
  57.     fn new(path: &str) -> Result<DirectoryIterator, String> {
  58.         // Call opendir and return a Ok value if that worked,
  59.         // otherwise return Err with a message.
  60.         let path =
  61.             CString::new(path).map_err(|err| format!("Invalid path: {err}"))?;
  62.         // SAFETY: path.as_ptr() cannot be NULL.
  63.         let dir = unsafe { ffi::opendir(path.as_ptr()) };
  64.         if dir.is_null() {
  65.             Err(format!("Could not open {path:?}"))
  66.         } else {
  67.             Ok(DirectoryIterator { path, dir })
  68.         }
  69.     }
  70. }
  71. impl Iterator for DirectoryIterator {
  72.     type Item = OsString;
  73.     fn next(&mut self) -> Option<OsString> {
  74.         // Keep calling readdir until we get a NULL pointer back.
  75.         // SAFETY: self.dir is never NULL.
  76.         let dirent = unsafe { ffi::readdir(self.dir) };
  77.         if dirent.is_null() {
  78.             // We have reached the end of the directory.
  79.             return None;
  80.         }
  81.         // SAFETY: dirent is not NULL and dirent.d_name is NUL
  82.         // terminated.
  83.         let d_name = unsafe { CStr::from_ptr((*dirent).d_name.as_ptr()) };
  84.         let os_str = OsStr::from_bytes(d_name.to_bytes());
  85.         Some(os_str.to_owned())
  86.     }
  87. }
  88. impl Drop for DirectoryIterator {
  89.     fn drop(&mut self) {
  90.         // Call closedir as needed.
  91.         // SAFETY: self.dir is never NULL.
  92.         if unsafe { ffi::closedir(self.dir) } != 0 {
  93.             panic!("Could not close {:?}", self.path);
  94.         }
  95.     }
  96. }
  97. fn main() -> Result<(), String> {
  98.     let iter = DirectoryIterator::new(".")?;
  99.     println!("files: {:#?}", iter.collect::<Vec<_>>());
  100.     Ok(())
  101. }
  102. #[cfg(test)]
  103. mod tests {
  104.     use super::*;
  105.     use std::error::Error;
  106.     #[test]
  107.     fn test_nonexisting_directory() {
  108.         let iter = DirectoryIterator::new("no-such-directory");
  109.         assert!(iter.is_err());
  110.     }
  111.     #[test]
  112.     fn test_empty_directory() -> Result<(), Box<dyn Error>> {
  113.         let tmp = tempfile::TempDir::new()?;
  114.         let iter = DirectoryIterator::new(
  115.             tmp.path().to_str().ok_or("Non UTF-8 character in path")?,
  116.         )?;
  117.         let mut entries = iter.collect::<Vec<_>>();
  118.         entries.sort();
  119.         assert_eq!(entries, &[".", ".."]);
  120.         Ok(())
  121.     }
  122.     #[test]
  123.     fn test_nonempty_directory() -> Result<(), Box<dyn Error>> {
  124.         let tmp = tempfile::TempDir::new()?;
  125.         std::fs::write(tmp.path().join("foo.txt"), "The Foo Diaries\n")?;
  126.         std::fs::write(tmp.path().join("bar.png"), "<PNG>\n")?;
  127.         std::fs::write(tmp.path().join("crab.rs"), "//! Crab\n")?;
  128.         let iter = DirectoryIterator::new(
  129.             tmp.path().to_str().ok_or("Non UTF-8 character in path")?,
  130.         )?;
  131.         let mut entries = iter.collect::<Vec<_>>();
  132.         entries.sort();
  133.         assert_eq!(entries, &[".", "..", "bar.png", "crab.rs", "foo.txt"]);
  134.         Ok(())
  135.     }
  136. }