1 个不稳定版本
0.1.0 | 2024年4月9日 |
---|
#1869 in 数据结构
在 bndpresbufq 中使用
9KB
96 行
有限队列
LimQ 是一个可以配置以存储最大元素数量的队列。
lib.rs
:
LimQ 是一个队列(作为 VecDeque
的包装实现),支持可选的最大元素数量约束。
而不是提供传统的 push()
方法来向队列中添加元素,LimQ 实现了 [LimQ::try_push()
] 和 [LimQ::force_push()
]. 如果没有启用队列限制,这两个操作与传统的 push()
一样。当设置限制并达到限制时,try_push()
将失败,返回输入元素。 force_push()
将强制添加新元素,同时丢弃下一个要出队的元素。
use limq::LimQ;
// Construct a queue with a maximum 2 element length limit
let mut q: LimQ<u32> = LimQ::new(Some(2));
// Add elements to fill up to queue
q.try_push(1).unwrap();
q.force_push(2);
// Fail to add a new node
assert_eq!(q.try_push(3), Err(3));
// Forcibly add node; expelling the oldest node
q.force_push(4);
// Remaining nodes should be 2 and 4
assert_eq!(q.pop(), Some(2));
assert_eq!(q.pop(), Some(4));
assert_eq!(q.pop(), None);