6个版本 (3个破坏性更新)
使用旧Rust 2015
0.3.0 | 2024年3月28日 |
---|---|
0.2.2 | 2016年1月15日 |
0.2.1 | 2015年5月26日 |
0.1.0 | 2015年2月1日 |
0.0.2 | 2015年1月18日 |
#7 in #intrusive
每月下载 50 次
23KB
319 行
% containerof - 支持Rust中侵入式数据结构的宏。
侵入式结构是一种通用结构,直接嵌入到包含结构中,以便将这种通用功能添加到容器中。例如,可以使用侵入式“链接”结构来允许对象以链表形式组织
# #[macro_use]
extern crate containerof;
struct Link {
next: Option<ContainerLink>,
}
struct List {
head: Option<ContainerLink>,
tail: Option<ContainerLink>,
}
struct Container {
link: Link,
}
containerof_intrusive!(ContainerLink = Container:link::Link);
# fn main() {}
虽然此模块不提供链表实现(由于关注点分离的原因,我认为链表实现应属于单独的crate),但它确实提供了一些使用侵入式结构所需的抽象
containerof_field_offset!
宏,该宏用于识别包含结构中字段的地址。这本身并不太有用,但它是支持containerof_intrusive!
宏,该宏提供了一个新类型,用于描述“侵入式”字段和“容器”结构之间的转换。
使用方法
以下是一个使用侵入式链表的Church数实现的示例
#[macro_use]
extern crate containerof;
use containerof::*;
struct Church {
next: Option<ChurchLink>,
}
containerof_intrusive!(ChurchLink = Church:next::Option<ChurchLink>);
impl Church {
fn new() -> OwnBox<Church> {
unsafe { OwnBox::from_box(Box::new(Church { next: None })) }
}
fn push(next: OwnBox<Church>) -> OwnBox<Church> {
unsafe { OwnBox::from_box(Box::new(Church { next: Some(Intrusive::from_container(next)) })) }
}
fn pop(me: OwnBox<Church>) -> Option<OwnBox<Church>> {
let me = unsafe { me.into_box() };
match me.next {
None => None,
Some(x) => Some(unsafe { x.into_container() }),
}
}
}
# fn main() {}
概念
containerof
使用三个主要概念来处理侵入式结构
- 侵入式结构本身(在上面的示例中为
Church.next
); - 包含结构(
Church
); - 转换类型,用于从字段获取容器,或反之(
ChurchLink
)。
此外,还有三个辅助结构用于管理侵入式结构的所有权和借用
OwnBox
,它是一个表示容器所有权的指针类型(即使你只有字段引用)。BorrowBox
,它是一个表示容器借用的指针类型。BorrowBoxMut
,它是一个表示容器可变借用的指针类型。
贡献
- 将其分叉( https://github.com/aidancully/containerof/fork )
- 创建你的功能分支(
git checkout -b my-new-feature
) - 提交您的更改(
git commit -am '添加一些功能'
) - 推送到分支(
git push origin my-new-feature
) - 创建新的Pull Request
无运行时依赖
~190KB