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 在 过程宏 中
每月2,150次下载
在 3 个crate中使用(通过 kernel_guard)
11KB
161 行
crate_interface
提供了一种在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