5个版本 (稳定版)
| 2.0.2 | 2019年6月16日 |
|---|---|
| 2.0.1 | 2019年6月12日 |
| 1.0.0 | 2019年5月18日 |
| 0.1.0 | 2019年4月14日 |
在 数据结构 中排名 #1498
88KB
1.5K SLoC
restor
用Rust编写的动态资源存储系统。它支持存储多种类型和多个条目,并通过
RefCell、Mutex 和 RwLock(来自 parking_lot)实现动态借用检查。它还支持一次性提取和获取多个类型。
示例
use restor::{DynamicStorage, make_storage};
fn main() {
// Use the shorthand for creating storage with preallocated types
let x = make_storage!(DynamicStorage: usize, String);
// Insert some data into the storage, either many at once, or one
x.insert_many((0..10).collect::<Vec<usize>>()).unwrap();
x.insert("abc".to_string()).unwrap();
create_string(&x);
println!("{}", &*x.get::<&String>().unwrap());
}
fn create_string(x: &DynamicStorage) {
let mut mystring = x.get::<&mut String>().unwrap();
for i in x.get::<&[usize]>().unwrap().iter() {
*mystring = format!("{}, {}", &*mystring, i);
}
}
工作原理
BlackBox(或 DynamicStorage)的定义如下(大致如此)
struct BlackBox {
data: HashMap<TypeId, Box<dyn Unit>>
}
Unit 特质使我们能够抽象容器(在代码中称为 UnitStorage)的泛型类型,因此我们可以使用看似神奇的 Any 特质来将数据传入和传出它。当您将某物插入存储时,它会经历以下阶段
- 您的数据在
BlackBox::insert<T> - 被装箱成
Box<dyn Any> - 传递给
StorageUnit as dyn Unit - 尝试将其转换为
T或Vec<T> - 放入存储中的自己的位置或在
Vec中
依赖项
~1.5MB
~24K SLoC