9个稳定版本
| 1.4.4 | 2020年6月23日 |
|---|---|
| 1.3.3 | 2020年6月22日 |
#466 in 内存管理
30次每月下载
用于 khash
40KB
1.5K SLoC
malloc-array - Vec<T> 类似于 malloc() 包装器
此crate提供了一个类似 vec! 的宏 heap!,用于创建由 malloc() 和 free() 管理的数组。它还提供了一个容器类型 HeapArray<T>,作为这些的安全的包装器。
有关更多详细信息,请参阅文档。
宏用法
创建零初始化数组。
这些是用 calloc() 创建的。
heap![Type; size];
请注意,如果 Type 不支持零初始化,则丢弃或访问返回数组的任何元素是未定义行为。要无丢弃分配,请参阅相关函数 replace_and_forget
let mut array = heap![String; 3];
array.replace_and_forget(0, format!("snibbedy"));
array.replace_and_forget(1, format!("snab"));
array.replace_and_forget(2, format!(":D"));
drop(array); // This is now safe.
或者用迭代器初始化
库还提供了一个 InitIter 类型,它是 HeapArray<T> 的可变迭代器,允许您安全地初始化潜在的未初始化元素。
let mut array = heap![String; 10];
for mut init in array.initialise()
{
init.put(format!("string!"));
// Also see docs for `init::Init` type.
}
drop(array); // This is now safe.
填充迭代器
迭代器还提供了填充自身未初始化值的方法。
用 Clone 填充
array.initialise().fill("value".to_owned());
用lambda填充
array.initialise().fill_with(|| "value".to_owned());
用 Default 填充
array.initialise().fill_default();
未初始化内存
由于无法确定类型 T 是否支持零初始化,因此将内存清零视为使其未初始化。
array.initialise().uninit(); //Sets all the rest of the iterator bytes to 0.
创建已初始化数组。
这些是通过 malloc() 创建的,并使用 replace_and_forget(或者,对于 u8 大小的类型,使用 memset)进行设置。
heap![expression; size];
创建 n 元素数组。
这些是通过 malloc() 创建的,并使用 replace_and_forget 进行设置。
heap![expression_one, expression_two];
创建空数组。
这些可以通过 malloc(0) 创建,或者如果启用了 zst_noalloc 功能,则不会进行分配。
heap![];
zst_noalloc 默认启用,并导致具有 len_bytes() == 0 的实例返回由 malloc(0) 返回的悬空指针,而不是内部指针 NULL。这种行为可能不是期望的,如果不希望这样,请禁用默认功能。
在释放时丢弃
以这种方式创建的数组会以确保每个元素也被丢弃的方式进行丢弃。对于实现 Copy 特性的任何内容,这可能是多余的。为了避免这种情况,请将关键字 unsafe 传递给上述宏定义中的任何一个
let bytes = heap![unsafe u8; 32]; //`u8` does not need to be dropped.
let references = heap![unsafe ":D"; 10]; //Neither does `&'static str`.
请注意,如果类型实现了 Drop 特性,那么除非手动丢弃元素(见 into_iter),否则丢弃数组可能导致资源泄漏。
许可
用爱GPL <3
依赖项
~0.4–540KB
~14K SLoC