我确定那里有一些东西,但我错过了它的关键字:)
我想要一个Vec(或其他一些使用堆的类似结构)只能保存 N 个值,但具有以下扭曲:
如果容量已满,下一个.push()将删除第一个值。因此,结构将保持完整,但最新推送的值位于底部。
我可以 DIY 它,但我是 Rust 的新手,所以我担心我的实现既不高效也不优雅。
谢谢!
您正在寻找的数据结构是一个循环缓冲区。您可以在https://crates.io/上找到许多实现,但推出自己的实现也不难。这是您可以用作起点的最小实现:
#[derive(Debug)]
pub struct CircularBuffer<T> {
start: usize,
data: Vec<T>,
}
impl<T> CircularBuffer<T> {
pub fn new(capacity: usize) -> Self {
Self {
start: 0,
data: Vec::with_capacity(capacity),
}
}
pub fn push(&mut self, item: T) {
if self.data.len() < self.data.capacity() {
self.data.push(item);
} else {
self.data[self.start] = item;
self.start += 1;
if self.start == self.data.capacity() {
self.start = 0;
}
}
}
pub fn get(&self, index: usize) -> Option<&T> {
if index >= self.data.len() {
return None;
}
let mut index = index + self.start;
if index > self.data.capacity() {
index -= self.data.capacity()
}
self.data.get(index)
}
}
Run Code Online (Sandbox Code Playgroud)