3个版本
| 0.1.2 | 2023年8月31日 |
|---|---|
| 0.1.1 | 2023年8月30日 |
| 0.1.0 | 2023年8月29日 |
#598 in 内存管理
11KB
233 行
type-handle
一个小巧的Rust库,导出Handle<T>和RCHandle<T>。可用于封装原生ffi结构体/指针。
Handle和RCHandle都实现了Clone,其中Handle将克隆底层结构体实例(如果实现了Clone),而RCHandle将保留底层指针。
Handle和RCHandle默认通过send_sync功能实现了Send/Sync。
它们都实现了Deref和DerefMut,因此您可以通过句柄访问字段,就像在普通实例上那样。
示例
Handle<T>
#[derive(Clone)]
struct Animal {
is_dog: bool,
}
let animal = Animal { is_dog: false };
let cat = Handle::from_instance(animal);
// clone `cat` and mutate `is_dog`, note that `animal` is not mutable
let dog = handle.clone(); // this clones `Animal`, `Animal` must implement `Clone`
dog.is_dog = true;
RCHandle<T>(引用计数句柄)
// don't have to #[derive(Clone)] here!
struct Animal {
is_dog: bool,
}
let mut animal = Animal { is_dog: false };
let mut handle = RCHandle::from_ptr(&mut animal);
// note that `Animal` does not implement `Clone`, because
// cloning an `RCHandle` does not clone the underlying type
let mut handle2 = handle.clone();
handle2.is_dog = true;
assert!(handle.is_dog == handle2.is_dog);
测试
要运行测试,请运行cargo test。
许可协议
公有领域(Unlicense)。