I have a Vec
that is the allocation for a circular buffer. Let's assume the buffer is full, so there are no elements in the allocation that aren't in the circular buffer. I now want to turn that circular buffer into a Vec
where the first element of the circular buffer is also the first element of the Vec
. As an example I have this (allocating) function:
fn normalize(tail: usize, buf: Vec<usize>) -> Vec<usize> {
let n = buf.len();
buf[tail..n]
.iter()
.chain(buf[0..tail].iter())
.cloned()
.collect()
}
Obviously this can also be done without allocating anything, since we already have an allocation that is large enough, and we have a swap
operation to swap arbitrary elements of the allocation.
fn normalize(tail: usize, mut buf: Vec<usize>) -> Vec<usize> {
for _ in 0..tail {
for i in 0..(buf.len() - 1) {
buf.swap(i, i + 1);
}
}
buf
}
Sadly this requires buf.len() * tail
swap operations. I'm fairly sure it can be done in buf.len() + tail
swap operations. For concrete values of tail
and buf.len()
I have been able to figure out solutions, but I'm not sure how to do it in the general case.
My recursive partial solution can be seen in action.