4

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());
}

1 Answer 1

3

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());
}
Sign up to request clarification or add additional context in comments.

3 Comments

You might want to make pixel_number into pixel_count so that they match. Anyway, using the assert! makes the method I'm using perfect, thanks!
This no longer works in 0.12.0. Do you know if that is intentional?
@DrYap Indeed, it has changed, the keyword is now const. Thanks !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.