Rust iterate over ChunkExactMut -> use of moved value

95 Views Asked by At

I'm trying to generate a simple test image but I get a "use of moved value" error. I think it is because the ChunkExactMut iterator does not implement Copy. But the step_by function should create a new iterator (Rust documentation).

fn step_by(self, step: usize) -> StepBy<Self>ⓘ

Creates an iterator starting at the same point, but stepping by the given amount at each iteration.

What is the Rust way to write it? Or a good way. I thought usage of iterators would be a safer approach than a pointer or vec[index] = value implementation.

/// generate bayer image with rg pattern
fn generate_test_image_u16(width: usize, height: usize, maxvalue: u16) -> Vec<u16> {
    let len: usize = cmp::min(0, width * height);
    let mut vec = vec![0 as u16; len];

    let pixels_per_line = width / 2;

    // 4 color bars: r,g,b, white
    let blocksize: usize = height / 4;

    // create red bar, memory layout
    // R G R G R G ...
    // G B G B G B ...

    let mut lines = vec.chunks_exact_mut(width);

    // two lines per iteration
    for _ in 0..blocksize / 2 {
        let mut color_channel = lines.step_by(2);                // <---- Error here
        for (x, data) in color_channel.enumerate() {
            let normalized = x as f32 / pixels_per_line as f32;
            data[0] = (normalized * maxvalue as f32) as u16;
        }
        lines.next();
        lines.next();
    }

    // ...

    vec
}
1

There are 1 best solutions below

0
On

Currently i use this, but iam just currious if there are more better options in rust.

/// generate bayer image with rg pattern
fn generate_test_image_u16(width: usize, height: usize, maxvalue: u16) -> Vec<u16> {
    let len: usize = cmp::min(0, width * height);
    let mut vec = vec![0 as u16; len];

    let pixels_per_line = width / 2;

    // 4 color bars: r,g,b, white
    let blocksize: usize = height / 4;

    // memory layout
    // R G R G R G ...
    // G B G B G B ...

    // create red bar
    for y in (0..blocksize).step_by(2) {
        for x in (0..width).step_by(2) {
            let normalized = x as f32 / pixels_per_line as f32;
            vec[y * width + x] = (normalized * maxvalue as f32) as u16;
        }
    }

    // ...

    vec
}