安全なFFIラッパ

Rust は、foreign function interface(FFI)を介して関数を呼び出すための優れたサポートを備えています。これを使って、C からディレクトリ内のファイル名を読み取るときに使用する libc 関数の安全なラッパーを構築します。

以下のマニュアルページを参照するとよいでしょう。

また、std::ffi モジュールにも目を通してください。そこには、この演習で必要になるいくつかの文字列型があります。

エンコード使う
strStringUTF-8Rust におけるテキスト処理
CStrCStringNUL終端文字列C 関数とのやり取り
OsStrOsStringOS 固有OS とのやり取り

これらすべての型の間で変換を行います。

  • &str から CString: 末尾の \0 文字のための領域を確保する必要があります。
  • CString から *const c_char: C 関数を呼び出すにはポインタが必要です。
  • *const c_char から &CStr: 末尾の \0 文字を見つけられるものが必要です。
  • &CStr から &[u8]: バイトスライスは「何らかの未知のデータ」に対する汎用的なインターフェースです。
  • &[u8] から &OsStr: &OsStrOsString への途中段階です。これを作成するには OsStrExt を使ってください。
  • &OsStr から OsString: &OsStr 内のデータを複製して、これを返せるようにし、さらに readdir を再度呼び出せるようにする必要があります。

Nomicon にも、FFI に関する非常に有用な章があります。

以下のコードを https://play.rust-lang.org/ にコピーし、不足している関数とメソッドを埋めてください。

// Copyright 2023 Google LLC
// SPDX-License-Identifier: Apache-2.0

// TODO: 実装が完了したらこれを削除してください。
#![allow(unused_imports, unused_variables, dead_code)]

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

    // Opaque type. See 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)>,
    }

    // Layout according to the Linux man page for readdir(3), where ino_t and
    // off_t are resolved according to the definitions in
    // /usr/include/x86_64-linux-gnu/{sys/types.h, bits/typesizes.h}.
    #[cfg(not(target_os = "macos"))]
    #[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],
    }

    // Layout according to the macOS man page for dir(5).
    #[cfg(target_os = "macos")]
    #[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],
    }

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

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

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

        pub unsafe 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> {
        // Call opendir and return a Ok value if that worked,
        // otherwise return Err with a message.
        todo!()
    }
}

impl Iterator for DirectoryIterator {
    type Item = OsString;
    fn next(&mut self) -> Option<OsString> {
        // Keep calling readdir until we get a NULL pointer back.
        todo!()
    }
}

impl Drop for DirectoryIterator {
    fn drop(&mut self) {
        // Call closedir as needed.
        todo!()
    }
}

fn main() -> Result<(), String> {
    let iter = DirectoryIterator::new(".")?;
    println!("files: {:#?}", iter.collect::<Vec<_>>());
    Ok(())
}

FFI バインディングのコードは、通常、ここで行っているように手作業で書くのではなく、bindgen のようなツールによって生成されます。ただし、bindgen はオンラインの playground では実行できません。