ํ•ด๋‹ต

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(())
    }
}