7个版本
0.9.30 | 2023年6月30日 |
---|---|
0.9.23 | 2023年6月30日 |
#190 在 内存管理
21KB
393 行
Memory Storage
与Vec类似的内存存储,删除项时不会将删除项后面的所有项左移,并且不会使它们的ID失效。它允许您以高速删除项并通过添加它们后返回的ID访问项。
何时使用?
- 当需要尽可能快地删除/添加项时
- 当需要以高速访问项时
- 当您不想为访问项生成自己的ID时
- 当您无法访问分配器时
使用数组的示例
use memory_storage::new_with_array;
let mut memory_storage = new_with_array::<i32, 3>();
let id_of_one = memory_storage.insert(1)
.expect("Something went wrong!");
let id_of_two = memory_storage.insert(2)
.expect("Something went wrong!");
let id_of_three = memory_storage.insert(3)
.expect("Something went wrong!");
// We are at max capacity!
assert!(memory_storage.insert(4).is_err());
let two = memory_storage.remove(id_of_two);
let id_of_four = memory_storage.insert(4)
.expect("Something went wrong!");
let three = *memory_storage.get(id_of_three)
.expect("Something went wrong!");
assert_eq!(three, 3);
使用vec的示例(仅当有'alloc'特性时)
// Only with 'alloc' feature on!
use memory_storage::vec::new_with_fixed_capacity_vec;
use memory_storage::vec::new_with_vec;
// Create a MemoryStorage using a vec with a fixed size of 3.
let fixed_size_vec_memory_storage = new_with_fixed_capacity_vec::<()>(3);
// MemoryStorage using a vec allowing to allocate more space.
// Here we create an instance with the size of 1 (which can be increased).
let mut vec_memory_storage = new_with_vec(1);
let id_of_one = vec_memory_storage.push(1);
let id_of_two = vec_memory_storage.push(2);
let id_of_three = vec_memory_storage.push(3);
let three = *vec_memory_storage.get(id_of_three)
.expect("Something went wrong!");
assert_eq!(three, 3);