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. ```
unsafe extern "C" {
```
39. ```
pub unsafe fn opendir(s: *const c_char) -> *mut DIR;
```
41. ```
#[cfg(not(all(target_os = "macos", target_arch = "x86_64")))]
```
42. ```
pub unsafe 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 unsafe fn readdir(s: *mut DIR) -> *const dirent;
```
53. ```
pub unsafe 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. ```
// SAFETY: self.dir is never NULL.
```
104. ```
if unsafe { ffi::closedir(self.dir) } != 0 {
```
105. ```
panic!("Could not close {:?}", self.path);
```
106. ```
}
```
107. ```
}
```
108. ```
}
```
110. ```
fn main() -> Result<(), String> {
```
111. ```
let iter = DirectoryIterator::new(".")?;
```
112. ```
println!("files: {:#?}", iter.collect::<Vec<_>>());
```
113. ```
Ok(())
```
114. ```
}
```
116. ```
#[cfg(test)]
```
117. ```
mod tests {
```
118. ```
use super::*;
```
119. ```
use std::error::Error;
```
121. ```
#[test]
```
122. ```
fn test_nonexisting_directory() {
```
123. ```
let iter = DirectoryIterator::new("no-such-directory");
```
124. ```
assert!(iter.is_err());
```
125. ```
}
```
127. ```
#[test]
```
128. ```
fn test_empty_directory() -> Result<(), Box<dyn Error>> {
```
129. ```
let tmp = tempfile::TempDir::new()?;
```
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, &[".", ".."]);
```
136. ```
Ok(())
```
137. ```
}
```
139. ```
#[test]
```
140. ```
fn test_nonempty_directory() -> Result<(), Box<dyn Error>> {
```
141. ```
let tmp = tempfile::TempDir::new()?;
```
142. ```
std::fs::write(tmp.path().join("foo.txt"), "The Foo Diaries\n")?;
```
143. ```
std::fs::write(tmp.path().join("bar.png"), "<PNG>\n")?;
```
144. ```
std::fs::write(tmp.path().join("crab.rs"), "//! Crab\n")?;
```
145. ```
let iter = DirectoryIterator::new(
```
146. ```
tmp.path().to_str().ok_or("Non UTF-8 character in path")?,
```
147. ```
)?;
```
148. ```
let mut entries = iter.collect::<Vec<_>>();
```
149. ```
entries.sort();
```
150. ```
assert_eq!(entries, &[".", "..", "bar.png", "crab.rs", "foo.txt"]);
```
151. ```
Ok(())
```
152. ```
}
```
153. ```
}
```