mod ffi {
use std::os::raw::{c_char, c_int};
#[cfg(not(target_os = "๋งคํฌ๋ก"))]
use std::os::raw::{c_long, c_uchar, c_ulong, c_ushort};
// ๋ถํฌ๋ช
ํ์
์
๋๋ค. https://doc.rust-lang.org/nomicon/ffi.html์ ์ฐธ๊ณ ํ์ธ์.
#[repr(C)]
pub struct DIR {
_data: [u8; 0],
_marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>,
}
// readdir(3)์ Linux man ํ์ด์ง์ ๋ฐ๋ฅธ ๋ ์ด์์์
๋๋ค.
// ์ฌ๊ธฐ์ ino_t ๋ฐ off_t๋
// /usr/include/x86_64-linux-gnu/{sys/types.h, bits/typesizes.h}์ ์ ์์ ๋ฐ๋ผ ํ์ธ๋ฉ๋๋ค.
#[cfg(not(target_os = "๋งคํฌ๋ก"))]
#[repr(C)]
pub struct dirent {
pub d_ino: c_ulong,
pub d_off: c_long,
pub d_reclen: c_ushort,
pub d_type: c_uchar,
pub d_name: [c_char; 256],
}
// dir(5)์ macOS man ํ์ด์ง์ ๋ฐ๋ฅธ ๋ ์ด์์์
๋๋ค.
#[cfg(all(target_os = "๋งคํฌ๋ก"))]
#[repr(C)]
pub struct dirent {
pub d_fileno: u64,
pub d_seekoff: u64,
pub d_reclen: u16,
pub d_namlen: u16,
pub d_type: u8,
pub d_name: [c_char; 1024],
}
extern "C" {
pub fn opendir(s: *const c_char) -> *mut DIR;
#[cfg(not(all(target_os = "๋งคํฌ๋ก", target_arch = "x86_64")))]
pub fn readdir(s: *mut DIR) -> *const dirent;
// https://github.com/rust-lang/libc/issues/414 ๋ฐ
// stat(2)์ ๊ดํ macOS man ํ์ด์ง์ _DARWIN_FEATURE_64_BIT_INODE ์น์
์ ์ฐธ๊ณ ํ์ธ์.
//
// ' ์ด ์
๋ฐ์ดํธ๊ฐ ์ ๊ณต๋๊ธฐ ์ ์ ์กด์ฌํ๋ ํ๋ซํผ์'
// Intel ๋ฐ PowerPC์ macOS (iOS/wearOS ๋ฑ์ด ์๋)๋ฅผ ์๋ฏธํฉ๋๋ค.
#[cfg(all(target_os = "๋งคํฌ๋ก", target_arch = "x86_64"))]
#[link_name = "readdir$INODE64"]
pub fn readdir(s: *mut DIR) -> *const dirent;
pub fn closedir(s: *mut DIR) -> c_int;
}
}
use std::ffi::{CStr, CString, OsStr, OsString};
use std::os::unix::ffi::OsStrExt;
#[derive(Debug)]
struct DirectoryIterator {
path: CString,
dir: *mut ffi::DIR,
}
impl DirectoryIterator {
fn new(path: &str) -> Result<DirectoryIterator, String> {
// opendir์ ํธ์ถํ๊ณ ์ ๋๋ก ์๋ํ๋ฉด Ok ๊ฐ์ ๋ฐํํ๊ณ
// ๊ทธ๋ ์ง ์์ผ๋ฉด ๋ฉ์์ง์ ํจ๊ป Err์ ๋ฐํํฉ๋๋ค.
let path =
CString::new(path).map_err(|err| format!("์๋ชป๋ ๊ฒฝ๋ก: {err}"))?;
// SAFETY: path.as_ptr()์ NULL์ผ ์ ์์ต๋๋ค.
let dir = unsafe { ffi::opendir(path.as_ptr()) };
if dir.is_null() {
Err(format!("{:?}์(๋ฅผ) ์ด ์ ์์ต๋๋ค.", path))
} else {
Ok(DirectoryIterator { path, dir })
}
}
}
impl Iterator for DirectoryIterator {
type Item = OsString;
fn next(&mut self) -> Option<OsString> {
// NULL ํฌ์ธํฐ๋ฅผ ๋ค์ ์ป์ ๋๊น์ง readdir์ ๊ณ์ ํธ์ถํฉ๋๋ค.
// SAFETY: self.dir์ NULL์ด ์๋๋๋ค.
let dirent = unsafe { ffi::readdir(self.dir) };
if dirent.is_null() {
// ๋๋ ํฐ๋ฆฌ์ ๋์ ๋๋ฌํ์ต๋๋ค.
return None;
}
// SAFETY: dirent๋ NULL์ด ์๋๋ฉฐ dirent.d_name์ NUL
// ์ข
๋ฃ๋ฉ๋๋ค.
let d_name = unsafe { CStr::from_ptr((*dirent).d_name.as_ptr()) };
let os_str = OsStr::from_bytes(d_name.to_bytes());
Some(os_str.to_owned())
}
}
impl Drop for DirectoryIterator {
fn drop(&mut self) {
// ํ์์ ๋ฐ๋ผ closedir์ ํธ์ถํฉ๋๋ค.
if !self.dir.is_null() {
// SAFETY: self.dir์ NULL์ด ์๋๋๋ค.
if unsafe { ffi::closedir(self.dir) } != 0 {
panic!("{:?}์(๋ฅผ) ๋ซ์ ์ ์์ต๋๋ค.", self.path);
}
}
}
}
fn main() -> Result<(), String> {
let iter = DirectoryIterator::new(".")?;
println!("ํ์ผ: {:#?}", iter.collect::<Vec<_>>());
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::error::Error;
#[test]
fn test_nonexisting_directory() {
let iter = DirectoryIterator::new("no-such-directory");
assert!(iter.is_err());
}
#[test]
fn test_empty_directory() -> Result<(), Box<dyn Error>> {
let tmp = tempfile::TempDir::new()?;
let iter = DirectoryIterator::new(
tmp.path().to_str().ok_or("๊ฒฝ๋ก์ UTF-8์ด ์๋ ๋ฌธ์๊ฐ ์์")?,
)?;
let mut entries = iter.collect::<Vec<_>>();
entries.sort();
assert_eq!(entries, &[".", ".."]);
Ok(())
}
#[test]
fn test_nonempty_directory() -> Result<(), Box<dyn Error>> {
let tmp = tempfile::TempDir::new()?;
std::fs::write(tmp.path().join("foo.txt"), "Foo ๋ค์ด์ด๋ฆฌ\n")?;
std::fs::write(tmp.path().join("bar.png"), "<PNG>\n")?;
std::fs::write(tmp.path().join("crab.rs"), "//! Crab\n")?;
let iter = DirectoryIterator::new(
tmp.path().to_str().ok_or("๊ฒฝ๋ก์ UTF-8์ด ์๋ ๋ฌธ์๊ฐ ์์")?,
)?;
let mut entries = iter.collect::<Vec<_>>();
entries.sort();
assert_eq!(entries, &[".", "..", "bar.png", "crab.rs", "foo.txt"]);
Ok(())
}
}