解答

  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. extern "C" {
  35. pub fn opendir(s: *const c_char) -> *mut DIR;
  36. #[cfg(not(all(target_os = "macos", target_arch = "x86_64")))]
  37. pub 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 fn readdir(s: *mut DIR) -> *const dirent;
  46. pub 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. if !self.dir.is_null() {
  92. // SAFETY: self.dir is not NULL.
  93. if unsafe { ffi::closedir(self.dir) } != 0 {
  94. panic!("Could not close {:?}", self.path);
  95. }
  96. }
  97. }
  98. }
  99. fn main() -> Result<(), String> {
  100. let iter = DirectoryIterator::new(".")?;
  101. println!("files: {:#?}", iter.collect::<Vec<_>>());
  102. Ok(())
  103. }
  104. #[cfg(test)]
  105. mod tests {
  106. use super::*;
  107. use std::error::Error;
  108. #[test]
  109. fn test_nonexisting_directory() {
  110. let iter = DirectoryIterator::new("no-such-directory");
  111. assert!(iter.is_err());
  112. }
  113. #[test]
  114. fn test_empty_directory() -> Result<(), Box<dyn Error>> {
  115. let tmp = tempfile::TempDir::new()?;
  116. let iter = DirectoryIterator::new(
  117. tmp.path().to_str().ok_or("Non UTF-8 character in path")?,
  118. )?;
  119. let mut entries = iter.collect::<Vec<_>>();
  120. entries.sort();
  121. assert_eq!(entries, &[".", ".."]);
  122. Ok(())
  123. }
  124. #[test]
  125. fn test_nonempty_directory() -> Result<(), Box<dyn Error>> {
  126. let tmp = tempfile::TempDir::new()?;
  127. std::fs::write(tmp.path().join("foo.txt"), "The Foo Diaries\n")?;
  128. std::fs::write(tmp.path().join("bar.png"), "<PNG>\n")?;
  129. std::fs::write(tmp.path().join("crab.rs"), "//! Crab\n")?;
  130. let iter = DirectoryIterator::new(
  131. tmp.path().to_str().ok_or("Non UTF-8 character in path")?,
  132. )?;
  133. let mut entries = iter.collect::<Vec<_>>();
  134. entries.sort();
  135. assert_eq!(entries, &[".", "..", "bar.png", "crab.rs", "foo.txt"]);
  136. Ok(())
  137. }
  138. }