4个版本
0.1.3 | 2021年12月12日 |
---|---|
0.1.2 | 2021年9月26日 |
0.1.1 | 2021年9月10日 |
0.1.0 | 2021年9月10日 |
#2434 在 数据结构
33KB
545 行
partial-array
- 用于 #![no_std]
的可能部分填充数组
这个crate提供了一种新的数据类型,类似于一个数组:即 PartialArray<N>
。它与数组等效,但条目数量可能在 0
到 N
之间。虽然它与 Vec<T>
有相似之处,但请注意,PartialArray
不增长其内存:它总是占用完整数组的内存(加上一些额外的计数器),并且它不能持有超过 N
个元素。这意味着它的内存是 完全静态 和 堆栈上的,使其可用于 #![no_std]
crate。
// some filter function, even numbers as an easy example
let f = |x: &i32| x % 2 == 0;
let array: partial_array::PartialArray<i32, 32> = (0..).take(32).filter(f).collect();
特性
这个crate相当简单,但有几个关键特性,可能使这个crate值得考虑
- 零依赖
#![no_std]
(为没有动态内存的嵌入式目标启用)- 只有少量
unsafe
代码,易于审计 - 开源
- 宽泛的许可
示例用法
这个新数据类型最有可能用于将迭代器收集到数组中,当长度未知但有一个上限时,例如。
use partial_array::PartialArray;
/// Take the first 10 elements of an iterator, that match the condition.
///
/// This can return less than 10 elements if the iterator has fewer than 10
/// items or there are less than 10 matching elements.
fn first_10_matching<T, I, F>(iter: I, check: F) -> PartialArray<T, 10>
where I: IntoIterator<Item = T>,
F: FnMut(&T) -> bool,
{
iter.into_iter().filter(check).take(10).collect()
}