porglezomp
porglezomp

Reputation: 1349

Create array with same length

I'm writing something that's writing images with lodepng-rust, and I'd like to work with pixels instead of u8s. I've created a struct

struct Pixel {r: u8, g: u8, b: u8}

and am building an array of u8s out of the elements of the array. Since I'm making the array by hand right now, I'm in the strange situation of needing to make the other array by hand as well. Is there a way I can create an array that's three times the length of the pixel array at compile time? Something like

let data: [u8; other_array.len()*3];

Which doesn't work because .len() isn't a compile time constant. The runtime cost doesn't really matter to me in this case, but if I could have the sizes related it would feel cleaner (and I might need the performance in the future).

Edit: The solution I'm using is based on Levans's answer. For people not initializing your array by hand, just follow Levans. I initialize my first array by hand, but set the type to use the length specified in pixel_count so that it'll catch the wrong pixel_count at compile time. I create the second array with that constant, and then assert that the lengths have the right ratio. My minimal example looks like this:

struct Pixel {r: u8, g: u8, b: u8}
const pixel_count: usize = 4;

fn main() {
    let pixel_data = [Pixel; pixel_count] = [
        Pixel {r: 255, g: 0, b: 0},
        Pixel {r: 0, g: 255, b: 0},
        Pixel {r: 0, g: 0, b: 255},
        Pixel {r: 0, g: 99, b: 99},
    ];
    let mut data = [0u8; pixel_count*3];
    assert_eq!(pixel_data.len()*3, data.len());
}

Upvotes: 4

Views: 1867

Answers (1)

Levans
Levans

Reputation: 14992

The easiest way for you to create size-related arrays would be to store the initial size as a const item : they are compile-time constants :

const pixel_count: uint = 42;

struct Pixel { r: u8, g: u8, b: u8 }

fn main() {
    let pixels = [Pixel { r: 0, g: 0, b: 0 }, ..pixel_count];
    let raw_data = [0u8, ..pixel_count * 3];
    assert!(pixels.len() * 3 == raw_data.len());
}

Upvotes: 3

Related Questions