#vector #dynamic #dyn #list #memory-block #heap-allocated #heap-memory

dynvec

此crate提供了类似向量的 DynVec 类型,用于存储任何数据类型

5 个发布版本

0.1.4 2020年12月28日
0.1.3 2020年12月26日
0.1.2 2020年12月26日
0.1.1 2020年12月22日
0.1.0 2020年12月22日

数据结构 中排名第 2198

每月下载 21
用于 siraph

MIT 许可证

37KB
698

Docs.rs

此crate dynvec 提供了类似向量的 DynVec 类型,用于存储任何数据类型。

默认情况下,DynVec 使用系统块,这些块在需要时在堆上分配,但可以使用 RawDynVec 结构和 Region 来更改。

目前实现了三种类型的区域。

  • Block:一个固定大小的内存块
  • Chunks:当一个块满时分配 Block(块)的区域
  • Global:一个简单的区域,映射到rust的分配器(每个项目都分配在堆内存的任何位置)。

示例

使用默认的 DynVec

use dynvec::DynVec;

// Create an empty `DynVec`
let mut my_vec = DynVec::new();

// By default, each chunk will be allocated with a size of 1024 bytes.
// This can be changed using the `DynVec::with_chunk_size` function.

// Items can be inserted into the vector
let handle_u8 = my_vec.insert(142u8);
let handle_str = my_vec.insert("Hello, world!");
let handle_vec = my_vec.insert(vec![1, 2, 3]);

// They can be accessed normally using indexing operations
my_vec[handle_vec].push(4);
assert_eq!(my_vec[handle_u8], 142);
assert_eq!(my_vec[handle_str], "Hello, world!");
assert_eq!(&my_vec[handle_vec][..], &[1, 2, 3, 4][..]);

// Removing them is just as easy
let vector = my_vec.remove(handle_vec).unwrap();
assert_eq!(&vector[..], &[1, 2, 3, 4][..]);

// The vector can be cleared (everything gets properly dropped)
my_vec.clear();

使用另一种类型的区域

use dynvec::{RawDynVec, Global};

// This is basically a vector of boxes.
let mut my_vec = RawDynVec::with_region(Global::default());
my_vec.insert(42);
my_vec.insert("Hello");

您可能希望避免在各个地方使用类型化句柄。您可以使用原始句柄

use dynvec::DynVec;
    
let mut my_vec = DynVec::new();
let mut handles = Vec::new();

handles.push(my_vec.insert("ABC").raw());
handles.push(my_vec.insert(64u8).raw());
handles.push(my_vec.insert(String::from("BDE")).raw());

for handle in handles {
    // This returns nothing
    // We do not know the type of the item anymore
    // The item gets properly dropped though
    my_vec.remove_raw(handle).unwrap();
}

注意

尽管它根本不是一个向量,但我仍然使用 DynVec 这个名字,因为这使它更容易理解它的功能。

无运行时依赖