简体   繁体   中英

How do I convert Clamped<Vec<u8>> to Clamped<&mut [u8]> with Rust and web-sys?

I am manipulating pixel data using Rust and WebAssembly, and am struggling to create new ImageData with the manipulated pixels.

When I get my ImageData 's data, it returns a Clamped<Vec<u8>>

   fn get_buffer_image_data(&self) -> Clamped<Vec<u8>> {
    let image_data = match self.buffer_ctx.get_image_data(0.0, 0.0, 640.0, 480.0) {
        Ok(d) => d,
        Err(_err) => panic!("failed to fetch buffer image data")
    };
    
    image_data.data()
}

I manipulate the pixel data in another function, and then attempt to create new ImageData with these manipulated pixels. The problem is that I can only create new ImageData with Clamped<&mut [u8]>

    fn create_image_data(&self, data: Clamped<Vec<u8>>) {
        let imageData = ImageData::new_with_u8_clamped_array_and_sh(data, 640, 480);
    }

However, the error I receive is:

mismatched types

expected `&mut [u8]`, found struct `std::vec::Vec`

note: expected struct `wasm_bindgen::Clamped<&mut [u8]>`
         found struct `wasm_bindgen::Clamped<std::vec::Vec<u8>>`

I think I need to convert one type to another. How do I convert efficiently? I have been trying this for a while and I am stuck. The only solution I have is to send the entire Uint8ClampedArray to wasm from my JS. Here is a code example you can use. Note, if you clone this repo please checkout the branch problem https://github.com/Fallenstedt/rotated-pixels/blob/problem/src/pixel_rotator.rs#L42-L44

If you look at the source code for Clamped , you'll see that it is just a wrapper around T .

pub struct Clamped<T>(pub T);

Because the inner T is public, you can perform any operations on it, such as converting a Vec to a slice:

let slice_data: &mut [u8] = &mut data.0[..];

You can then wrap slice_data in a new instance of Clamped , and pass it to ImageData :

fn create_image_data(&self, data: Clamped<Vec<u8>>) {
  let slice_data = Clamped(&mut data.0[..]);
  let imageData = ImageData::new_with_u8_clamped_array_and_sh(slice_data, 640, 480);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM