Day 3 Afternoon Exercises

Safe FFI Wrapper

(back to exercise)

  1. // Copyright 2022 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // ANCHOR: ffi
  15. mod ffi {
  16. use std::os::raw::{c_char, c_int, c_long, c_ulong, c_ushort};
  17. // Opaque type. See https://doc.rust-lang.org/nomicon/ffi.html.
  18. #[repr(C)]
  19. pub struct DIR {
  20. _data: [u8; 0],
  21. _marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>,
  22. }
  23. // Layout as per readdir(3) and definitions in /usr/include/x86_64-linux-gnu.
  24. #[repr(C)]
  25. pub struct dirent {
  26. pub d_ino: c_long,
  27. pub d_off: c_ulong,
  28. pub d_reclen: c_ushort,
  29. pub d_type: c_char,
  30. pub d_name: [c_char; 256],
  31. }
  32. extern "C" {
  33. pub fn opendir(s: *const c_char) -> *mut DIR;
  34. pub fn readdir(s: *mut DIR) -> *const dirent;
  35. pub fn closedir(s: *mut DIR) -> c_int;
  36. }
  37. }
  38. use std::ffi::{CStr, CString, OsStr, OsString};
  39. use std::os::unix::ffi::OsStrExt;
  40. #[derive(Debug)]
  41. struct DirectoryIterator {
  42. path: CString,
  43. dir: *mut ffi::DIR,
  44. }
  45. // ANCHOR_END: ffi
  46. // ANCHOR: DirectoryIterator
  47. impl DirectoryIterator {
  48. fn new(path: &str) -> Result<DirectoryIterator, String> {
  49. // Call opendir and return a Ok value if that worked,
  50. // otherwise return Err with a message.
  51. // ANCHOR_END: DirectoryIterator
  52. let path = CString::new(path).map_err(|err| format!("Invalid path: {err}"))?;
  53. // SAFETY: path.as_ptr() cannot be NULL.
  54. let dir = unsafe { ffi::opendir(path.as_ptr()) };
  55. if dir.is_null() {
  56. Err(format!("Could not open {:?}", path))
  57. } else {
  58. Ok(DirectoryIterator { path, dir })
  59. }
  60. }
  61. }
  62. // ANCHOR: Iterator
  63. impl Iterator for DirectoryIterator {
  64. type Item = OsString;
  65. fn next(&mut self) -> Option<OsString> {
  66. // Keep calling readdir until we get a NULL pointer back.
  67. // ANCHOR_END: Iterator
  68. // SAFETY: self.dir is never NULL.
  69. let dirent = unsafe { ffi::readdir(self.dir) };
  70. if dirent.is_null() {
  71. // We have reached the end of the directory.
  72. return None;
  73. }
  74. // SAFETY: dirent is not NULL and dirent.d_name is NUL
  75. // terminated.
  76. let d_name = unsafe { CStr::from_ptr((*dirent).d_name.as_ptr()) };
  77. let os_str = OsStr::from_bytes(d_name.to_bytes());
  78. Some(os_str.to_owned())
  79. }
  80. }
  81. // ANCHOR: Drop
  82. impl Drop for DirectoryIterator {
  83. fn drop(&mut self) {
  84. // Call closedir as needed.
  85. // ANCHOR_END: Drop
  86. if !self.dir.is_null() {
  87. // SAFETY: self.dir is not NULL.
  88. if unsafe { ffi::closedir(self.dir) } != 0 {
  89. panic!("Could not close {:?}", self.path);
  90. }
  91. }
  92. }
  93. }
  94. // ANCHOR: main
  95. fn main() -> Result<(), String> {
  96. let iter = DirectoryIterator::new(".")?;
  97. println!("files: {:#?}", iter.collect::<Vec<_>>());
  98. Ok(())
  99. }
  100. // ANCHOR_END: main