Hi Everyone! I'm know a bit or two about rust, but I found a problem and I have the feeling that I'm missing something and ask for your help.
I'm trying to port a C# code to Rust. Rust looks like a really fast language, and after some works with it, looks like a good choice to speed my program. But I can't find a way to create a Pool of reusable vectors. In C#, i have this algorithm.
// C# Source Code
var popLength = 1024;
//This with result an array with 1024 null items
var arr = ArrayPool<Individual>.Shared.Rent(popLength);
// Do a lot of operations, with each item of the array,
// like, initialize the individual, do some operations with each item, etc
// After all is done, I clean the array
for(var i =0; i < arr.Length; i++) {
// This helps the GC identify objects that can be discarded.
arr[i] = null;
}
// And return it to the pool, to be used again
ArrayPool<Individual>.Shared.Return(arr, true);
In rust I tried to mimic this behavior with a struct:
// Rust Code
use std::collections::VecDeque;
/// Structure to hold a lot of reusable vectors
pub struct VecPool<T> {
pool: VecDeque<Vec<T>>,
}
impl<T> VecPool<T> {
/// Create a new pool
pub fn new() -> Self {
Self {
pool: VecDeque::new(),
}
}
/// Rent a new vector
pub fn rent(&mut self, size: usize) -> Vec<T> {
match self.pool.pop_front() {
Some(mut p) => {
p.clear();
p
}
None => Vec::with_capacity(size),
}
}
/// Return a vector to the pool
pub fn put_back(&mut self, mut vec: Vec<T>) {
vec.clear();
self.pool.push_back(vec);
}
}
The problem that I have occurs when I try to return the vector to the pool. For example, when I try to execute an operation:
/// Execute an operation on the population
pub fn execute(
pool: &mut VecPool<Individual>,
population: &mut Vec<Individuals),
) {
let mut temp = pool.rent(population.len());
while temp.len() < poppulation.len() {
// Execute a lot of operations with each item of the population
// This is jsut an example, no the exact source code that I have
let new_ind = do_stuff(&population);
temp.push(new_ind)
}
population.clear();
population.extend(temp);
// This does not compile, because of the move
pool.put_back(temp);
}
The problem that I'm facing is: I cant find a way to move all contents from the temp array to the population, and after that, send the temp array to the pool to be re-utilized.
There is some way to accomplish this?
Thank you in advance!