arrayslistperformancerustvector

Batch-update adjacent elements in a Vec in Rust (for performance)


I'm building a little graphics library using minifb, essentially just drawing pixels to a framebuffer.
Currently, my code for blitting a rectangle to a Texture is as follows:

fn blit(&self, dest: &mut Texture) {                  
    for x: i32 in self.x..self.x+self.width {         
        for y: i32 in self.y..self.y+self.height {    
            dest.set(x, y, color: self.color.clone());
            // same as dest.pixels[y*dest.width+x]=color
            // but this checks for out-of-bound pixels.
        }                                             
    }                                                 
}                                                     

Obviously this is very inefficient as I need to loop through each pixel one-by-one.
I wondered if Rust had a method of setting a 'chunk' of the dest.pixels vector to a line of the rectangle pixels? So a single call could update, say, a line of 100 pixels? Something like Vec::update_from(&mut self, index, new_values).

For example, if I had two Vecs as follows:

let a = vec![2, 4, 5, 6, 7, 8, 10];
let b = vec![0, 1, 2];

I'd like to be able to start writing vec b into vec a at a specific index, e.g. index 3 (element 4). So the resulting vec would be [2, 4, 5, 0, 1, 2, 10].

If there is a way to mass-update elements in a vec with a single call, I'd really appreciate it :)

2nd request - how about other textures?

My code for blitting a texture (vec of pixels) to another texture is as follows:

fn blit(&self, dest: &mut Texture) {                                                       
    for y: i32 in 0i32..self.height as i32 {                                               
        for x: i32 in 0i32..self.width as i32 {                                            
            dest.set(x: x + self.x, y: y + self.y, color: self.get(x, y).unwrap().clone());
        }                                                                                  
    }                                                                                      
}                                                                                          

Would it also be possible to write in bulk (rows at a time instead of pixels) for different values?

Any help for either of these would be greatly appreciated, and I'm happy to answer any questions to clarify things.


Solution

  • To Vecs (or more precisely slices), yes, but I don't know about your texture library. Anyway this is copy_from_slice():

    a[3..][..b.len()].copy_from_slice(b);