Initialize Vec with Generic Default Values

I wrote a function to unswizzle (rearrange) a vector of image data, and it works great. The thing is, this this image data can either be a vector of raw pixel data (Vec::<Pixel>), or a vector of indices for looking up the pixel color from a color palette (Vec::<u8>). Here's a slightly modified version of the original unswizzle() function I wrote:

fn unswizzle(buffer: &Vec::<u8>, header: &Header) -> Vec::<u8> {
	let mut i = 0usize;
	let mut result = vec![buffer.len(); 0];

	for y in (0..header.height).step_by(SWIZZLE_HEIGHT) {
		for x in (0..header.width).step_by(SWIZZLE_WIDTH) {
			for tile_y in y..(y + SWIZZLE_HEIGHT) {
				for tile_x in x..(x + SWIZZLE_WIDTH) {
					if tile_x < header.width && tile_y < header.height {
						let index = (tile_y * header.width + tile_x);
						if let Some(v) = buffer.get(i) {
							result[index] = *v;
						}
					}

					i += 1;
				}
			}
		}
	}

	result
}

I'd like to change the buffer: &Vec::<u8> param to something like this: buffer: &Vec::<T>. Adding the generic param isn't difficult, but I'm not sure how to initialize let mut result = vec![buffer.len(); 0]; to provide a generic value. Zero works great for the u8 case, and I have Pixel::new() for the pixel case. I think I might need to take a slightly different approach.

You can require that T implements the Default trait.

Worked like a charm. I'm still figuring out traits and learning about all of the built-in ones.

Thanks again, Alice!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.