Safe FFI Wrapper

Rust has great support for calling functions through a foreign function interface (FFI). We will use this to build a safe wrapper for the libc functions you would use from C to read the names of files in a directory.

You will want to consult the manual pages:

You will also want to browse the std::ffi module. There you find a number of string types which you need for the exercise:

Types Encoding Use
str and String UTF-8 Text processing in Rust
CStr and CString NUL-terminated Communicating with C functions
OsStr and OsString OS-specific Communicating with the OS

You will convert between all these types:

  • &str to CString: you need to allocate space for a trailing \0 character,
  • CString to *const i8: you need a pointer to call C functions,
  • *const i8 to &CStr: you need something which can find the trailing \0 character,
  • &CStr to &[u8]: a slice of bytes is the universal interface for “some unknown data”,
  • &[u8] to &OsStr: &OsStr is a step towards OsString, use OsStrExt to create it,
  • &OsStr to OsString: you need to clone the data in &OsStr to be able to return it and call readdir again.

The Nomicon also has a very useful chapter about FFI.

Copy the code below to <https://play.rust-lang.org/> and fill in the missing functions and methods:

1. ```
   // TODO: remove this when you're done with your implementation.
   ```
2. ```
   #![allow(unused_imports, unused_variables, dead_code)]
   ```

4. ```
   mod ffi {
   ```
5. ```
       use std::os::raw::{c_char, c_int};
   ```
6. ```
       #[cfg(not(target_os = "macos"))]
   ```
7. ```
       use std::os::raw::{c_long, c_uchar, c_ulong, c_ushort};
   ```

9. ```
       // Opaque type. See https://doc.rust-lang.org/nomicon/ffi.html.
   ```
10. ```
        #[repr(C)]
    ```
11. ```
        pub struct DIR {
    ```
12. ```
            _data: [u8; 0],
    ```
13. ```
            _marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>,
    ```
14. ```
        }
    ```

16. ```
        // Layout according to the Linux man page for readdir(3), where ino_t and
    ```
17. ```
        // off_t are resolved according to the definitions in
    ```
18. ```
        // /usr/include/x86_64-linux-gnu/{sys/types.h, bits/typesizes.h}.
    ```
19. ```
        #[cfg(not(target_os = "macos"))]
    ```
20. ```
        #[repr(C)]
    ```
21. ```
        pub struct dirent {
    ```
22. ```
            pub d_ino: c_ulong,
    ```
23. ```
            pub d_off: c_long,
    ```
24. ```
            pub d_reclen: c_ushort,
    ```
25. ```
            pub d_type: c_uchar,
    ```
26. ```
            pub d_name: [c_char; 256],
    ```
27. ```
        }
    ```

29. ```
        // Layout according to the macOS man page for dir(5).
    ```
30. ```
        #[cfg(all(target_os = "macos"))]
    ```
31. ```
        #[repr(C)]
    ```
32. ```
        pub struct dirent {
    ```
33. ```
            pub d_fileno: u64,
    ```
34. ```
            pub d_seekoff: u64,
    ```
35. ```
            pub d_reclen: u16,
    ```
36. ```
            pub d_namlen: u16,
    ```
37. ```
            pub d_type: u8,
    ```
38. ```
            pub d_name: [c_char; 1024],
    ```
39. ```
        }
    ```

41. ```
        unsafe extern "C" {
    ```
42. ```
            pub unsafe fn opendir(s: *const c_char) -> *mut DIR;
    ```

44. ```
            #[cfg(not(all(target_os = "macos", target_arch = "x86_64")))]
    ```
45. ```
            pub unsafe fn readdir(s: *mut DIR) -> *const dirent;
    ```

47. ```
            // See https://github.com/rust-lang/libc/issues/414 and the section on
    ```
48. ```
            // _DARWIN_FEATURE_64_BIT_INODE in the macOS man page for stat(2).
    ```
49. ```
            //
    ```
50. ```
            // "Platforms that existed before these updates were available" refers
    ```
51. ```
            // to macOS (as opposed to iOS / wearOS / etc.) on Intel and PowerPC.
    ```
52. ```
            #[cfg(all(target_os = "macos", target_arch = "x86_64"))]
    ```
53. ```
            #[link_name = "readdir$INODE64"]
    ```
54. ```
            pub unsafe fn readdir(s: *mut DIR) -> *const dirent;
    ```

56. ```
            pub unsafe fn closedir(s: *mut DIR) -> c_int;
    ```
57. ```
        }
    ```
58. ```
    }
    ```

60. ```
    use std::ffi::{CStr, CString, OsStr, OsString};
    ```
61. ```
    use std::os::unix::ffi::OsStrExt;
    ```

63. ```
    #[derive(Debug)]
    ```
64. ```
    struct DirectoryIterator {
    ```
65. ```
        path: CString,
    ```
66. ```
        dir: *mut ffi::DIR,
    ```
67. ```
    }
    ```

69. ```
    impl DirectoryIterator {
    ```
70. ```
        fn new(path: &str) -> Result&lt;DirectoryIterator, String> {
    ```
71. ```
            // Call opendir and return a Ok value if that worked,
    ```
72. ```
            // otherwise return Err with a message.
    ```
73. ```
            unimplemented!()
    ```
74. ```
        }
    ```
75. ```
    }
    ```

77. ```
    impl Iterator for DirectoryIterator {
    ```
78. ```
        type Item = OsString;
    ```
79. ```
        fn next(&mut self) -> Option&lt;OsString> {
    ```
80. ```
            // Keep calling readdir until we get a NULL pointer back.
    ```
81. ```
            unimplemented!()
    ```
82. ```
        }
    ```
83. ```
    }
    ```

85. ```
    impl Drop for DirectoryIterator {
    ```
86. ```
        fn drop(&mut self) {
    ```
87. ```
            // Call closedir as needed.
    ```
88. ```
            unimplemented!()
    ```
89. ```
        }
    ```
90. ```
    }
    ```

92. ```
    fn main() -> Result<(), String> {
    ```
93. ```
        let iter = DirectoryIterator::new(".")?;
    ```
94. ```
        println!("files: {:#?}", iter.collect::&lt;Vec<_>>());
    ```
95. ```
        Ok(())
    ```
96. ```
    }
    ```