Implement support for Uint8ClampedArray

This commit implements support for binding APIs that take
`Uint8ClampedArray` in JS. This is pretty rare but comes up in a
`web-sys` binding or two, and we're now able to bind these APIs instead
of having to omit the bindings.

The `Uint8ClampedArray` type is bound by using the `Clamped` marker
struct in Rust. For example this is declaring a JS API that takes
`Uint8ClampedArray`:

    use wasm_bindgen::Clamped;

    #[wasm_bindgen]
    extern {
        fn takes_clamped(a: Clamped<&[u8]>);
    }

The `Clamped` type currently only works when wrapping the `&[u8]`, `&mut
[u8]`, and `Vec<u8>` types. Everything else will produce an error at
`wasm-bindgen` time.

Closes #421
This commit is contained in:
Alex Crichton
2018-09-24 13:49:12 -07:00
parent d10ca579e4
commit 7b495468f6
15 changed files with 169 additions and 60 deletions

View File

@ -19,7 +19,7 @@ extern crate wasm_bindgen_macro;
use core::cell::UnsafeCell;
use core::fmt;
use core::mem;
use core::ops::Deref;
use core::ops::{Deref, DerefMut};
use core::ptr;
use convert::FromWasmAbi;
@ -864,3 +864,32 @@ pub mod __rt {
FOO.store(0, Ordering::SeqCst);
}
}
/// A wrapper type around slices and vectors for binding the `Uint8ClampedArray`
/// array in JS.
///
/// If you need to invoke a JS API which must take `Uint8ClampedArray` array,
/// then you can define it as taking one of these types:
///
/// * `Clamped<&[u8]>`
/// * `Clamped<&mut [u8]>`
/// * `Clamped<Vec<u8>>`
///
/// All of these types will show up as `Uint8ClampedArray` in JS and will have
/// different forms of ownership in Rust.
#[derive(Copy, Clone, PartialEq, Debug, Eq)]
pub struct Clamped<T>(pub T);
impl<T> Deref for Clamped<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
impl<T> DerefMut for Clamped<T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.0
}
}