Hello. I know having multiple
mut references is not allowed in Rust. I'm trying to model some actual firmware behavior to show that Rust can replace the code in C/C++.
This is the broken code, which I want to fix somehow: Rust Playground
The system has allocated objects in
seq: Vec<Obj>. Instead of passing referenced in queues, I'm using index numbers from that Vec in queues.
The main idea of the algorithm is to "move numbers" from full Objects into empty. This loop must be fast and easy to read and understand.
Essentially, I need to execute the following:
let mut src = seq[q_full.pop()]; let mut dst = seq[q_empty.pop()]; dst.counter += src.counter; src.counter = 0;
In the real system, counters can be changed only by 1 at once with some additional logic.
The system has a guarantee that every object is located only in one of the 2 queues or outside of the queues during data processing.
But I can't borrow data from Vec by index as mutable more than one time. But my system guarantees that there are no more than 1 reference to the
seq array at any given time.
error[E0499]: cannot borrow `seq` as mutable more than once at a time --> src/main.rs:50:35 | 41 | let src_ref = &mut seq[src_idx]; | --- first mutable borrow occurs here ... 50 | let target_ref = &mut seq[target_idx]; | ^^^ second mutable borrow occurs here ... 53 | let limit = min(src.counter, MAX_COUNTER); | ----------- first borrow later used here
Are there any existing data structures or crates to allow something like this? Any techniques or workarounds?
One of the requirements that I have is that we should avoid using
seq as an array of pointers to heap allocated data. So, it must store data continuously without Box indirection.