#arceos #macro #api

过程宏 无std crate_interface

提供了一种在crate中定义接口(特质)的方法,但可以在任何crate中实现或使用它

4个版本

0.1.3 2024年7月30日
0.1.2 2024年7月11日
0.1.1 2023年5月3日
0.1.0 2023年5月3日

1621过程宏

Download history 56/week @ 2024-04-14 57/week @ 2024-04-21 348/week @ 2024-04-28 328/week @ 2024-05-05 129/week @ 2024-05-12 136/week @ 2024-05-19 294/week @ 2024-05-26 281/week @ 2024-06-02 99/week @ 2024-06-09 134/week @ 2024-06-16 520/week @ 2024-06-23 171/week @ 2024-06-30 266/week @ 2024-07-07 252/week @ 2024-07-14 684/week @ 2024-07-21 948/week @ 2024-07-28

每月2,150次下载
3 个crate中使用(通过 kernel_guard

GPL-3.0-or-later OR Apache-2…

11KB
161

crate_interface

Crates.io Docs.rs CI

提供了一种在crate中 定义 接口(特质)的方法,但可以在任何crate中 实现使用 它。它通常用于解决crate之间的 循环依赖 问题。

示例

// Define the interface
#[crate_interface::def_interface]
pub trait HelloIf {
    fn hello(&self, name: &str, id: usize) -> String;
}

// Implement the interface in any crate
struct HelloIfImpl;

#[crate_interface::impl_interface]
impl HelloIf for HelloIfImpl {
    fn hello(&self, name: &str, id: usize) -> String {
        format!("Hello, {} {}!", name, id)
    }
}

// Call `HelloIfImpl::hello` in any crate
use crate_interface::call_interface;
assert_eq!(
    call_interface!(HelloIf::hello("world", 123)),
    "Hello, world 123!"
);
assert_eq!(
    call_interface!(HelloIf::hello, "rust", 456), // another calling style
    "Hello, rust 456!"
);

实现

上述示例中的过程宏将生成以下代码

// #[def_interface]
pub trait HelloIf {
    fn hello(&self, name: &str, id: usize) -> String;
}

#[allow(non_snake_case)]
pub mod __HelloIf_mod {
    use super::*;
    extern "Rust" {
        pub fn __HelloIf_hello(name: &str, id: usize) -> String;
    }
}

struct HelloIfImpl;

// #[impl_interface]
impl HelloIf for HelloIfImpl {
    fn hello(&self, name: &str, id: usize) -> String {
        {
            #[export_name = "__HelloIf_hello"]
            extern "Rust" fn __HelloIf_hello(name: &str, id: usize) -> String {
                let _impl: HelloIfImpl = HelloIfImpl;
                _impl.hello(name, id)
            }
        }
        {
            format!("Hello, {} {}!", name, id)
        }
    }
}

// call_interface!
assert_eq!(
    unsafe { __HelloIf_mod::__HelloIf_hello("world", 123) },
    "Hello, world 123!"
);

依赖项

~260–700KB
~17K SLoC