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