1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
use crate::{qjs, ArrayBuffer, Ctx, Error, FromJs, Function, IntoJs, Object, Result, Value};
use std::{
    convert::TryFrom,
    marker::PhantomData,
    mem::{size_of, MaybeUninit},
    ops::Deref,
    ptr::null_mut,
    slice,
};

/// The trait which implements types which capable to be TypedArray items
///
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "array-buffer")))]
pub trait TypedArrayItem {
    const CLASS_NAME: &'static str;
}

macro_rules! typedarray_items {
    ($($name:ident: $type:ty,)*) => {
        $(impl TypedArrayItem for $type {
            const CLASS_NAME: &'static str = stringify!($name);
        })*
    };
}

typedarray_items! {
    Int8Array: i8,
    Uint8Array: u8,
    Int16Array: i16,
    Uint16Array: u16,
    Int32Array: i32,
    Uint32Array: u32,
    Float32Array: f32,
    Float64Array: f64,
    BigInt64Array: i64,
    BigUint64Array: u64,
}

/// Rust representation of a javascript objects of TypedArray classes.
///
/// | ES Type            | Rust Type             |
/// | ------------------ | --------------------- |
/// | `Int8Array`        | [`TypedArray<i8>`]    |
/// | `Uint8Array`       | [`TypedArray<u8>`]    |
/// | `Int16Array`       | [`TypedArray<i16>`]   |
/// | `Uint16Array`      | [`TypedArray<u16>`]   |
/// | `Int32Array`       | [`TypedArray<i32>`]   |
/// | `Uint32Array`      | [`TypedArray<u32>`]   |
/// | `Float32Array`     | [`TypedArray<f32>`]   |
/// | `Float64Array`     | [`TypedArray<f64>`]   |
/// | `BigInt64Array`    | [`TypedArray<i64>`]   |
/// | `BigUint64Array`   | [`TypedArray<u64>`]   |
///
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "array-buffer")))]
#[derive(Debug, PartialEq, Clone)]
#[repr(transparent)]
pub struct TypedArray<'js, T>(pub(crate) Object<'js>, PhantomData<T>);

impl<'js, T> TypedArray<'js, T> {
    /// Create typed array from vector data
    pub fn new(ctx: Ctx<'js>, src: impl Into<Vec<T>>) -> Result<Self>
    where
        T: Copy + TypedArrayItem,
    {
        let ab = ArrayBuffer::new(ctx, src)?;
        Self::from_arraybuffer(ab)
    }

    /// Create typed array from slice
    pub fn new_copy(ctx: Ctx<'js>, src: impl AsRef<[T]>) -> Result<Self>
    where
        T: Copy + TypedArrayItem,
    {
        let ab = ArrayBuffer::new_copy(ctx, src)?;
        Self::from_arraybuffer(ab)
    }

    /// Get the length of the typed array in elements.
    pub fn len(&self) -> usize {
        //Self::get_raw(&self.0).expect("Not a TypedArray").0
        let ctx = self.0.ctx;
        let value = self.0.as_js_value();
        unsafe {
            let val = qjs::JS_GetPropertyStr(ctx.as_ptr(), value, b"length\0".as_ptr() as *const _);
            assert!(qjs::JS_IsInt(val));
            qjs::JS_VALUE_GET_INT(val) as _
        }
    }

    /// Returns wether a typed array is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Reference to value
    #[inline]
    pub fn as_value(&self) -> &Value<'js> {
        self.0.as_value()
    }

    /// Convert into value
    #[inline]
    pub fn into_value(self) -> Value<'js> {
        self.0.into_value()
    }

    /// Convert from value
    pub fn from_value(value: Value<'js>) -> Result<Self>
    where
        T: TypedArrayItem,
    {
        Self::from_object(Object::from_value(value)?)
    }

    /// Reference as an object
    #[inline]
    pub fn as_object(&self) -> &Object<'js> {
        &self.0
    }

    /// Convert into an object
    #[inline]
    pub fn into_object(self) -> Object<'js> {
        self.0
    }

    /// Convert from an object
    pub fn from_object(object: Object<'js>) -> Result<Self>
    where
        T: TypedArrayItem,
    {
        let class: Function = object.ctx.globals().get(T::CLASS_NAME)?;
        if object.is_instance_of(class) {
            Ok(Self(object, PhantomData))
        } else {
            Err(Error::new_from_js("object", T::CLASS_NAME))
        }
    }

    /// Get underlaying ArrayBuffer
    pub fn arraybuffer(&self) -> Result<ArrayBuffer<'js>> {
        let ctx = self.0.ctx;
        let val = self.0.as_js_value();
        let buf = unsafe {
            let val =
                qjs::JS_GetTypedArrayBuffer(ctx.as_ptr(), val, null_mut(), null_mut(), null_mut());
            ctx.handle_exception(val)?;
            Value::from_js_value(ctx, val)
        };
        ArrayBuffer::from_value(buf)
    }

    /// Convert from an ArrayBuffer
    pub fn from_arraybuffer(arraybuffer: ArrayBuffer<'js>) -> Result<Self>
    where
        T: TypedArrayItem,
    {
        let ctx = arraybuffer.0.ctx;
        let ctor: Function = ctx.globals().get(T::CLASS_NAME)?;
        ctor.construct((arraybuffer,))
    }

    pub(crate) fn get_raw(val: &Value<'js>) -> Option<(usize, *mut T)> {
        let ctx = val.ctx;
        let val = val.as_js_value();
        let mut off = MaybeUninit::<qjs::size_t>::uninit();
        let mut len = MaybeUninit::<qjs::size_t>::uninit();
        let mut stp = MaybeUninit::<qjs::size_t>::uninit();
        let buf = unsafe {
            let val = qjs::JS_GetTypedArrayBuffer(
                ctx.as_ptr(),
                val,
                off.as_mut_ptr(),
                len.as_mut_ptr(),
                stp.as_mut_ptr(),
            );
            ctx.handle_exception(val).ok()?;
            Value::from_js_value(ctx, val)
        };
        let off = unsafe { off.assume_init() } as usize;
        let len = unsafe { len.assume_init() } as usize;
        let stp = unsafe { stp.assume_init() } as usize;
        if stp != size_of::<T>() {
            return None;
        }
        let (full_len, ptr) = ArrayBuffer::get_raw(&buf)?;
        if (off + len) > full_len {
            return None;
        }
        let len = len / size_of::<T>();
        let ptr = unsafe { ptr.add(off) } as *mut T;
        Some((len, ptr))
    }
}

impl<'js, T: TypedArrayItem> AsRef<[T]> for TypedArray<'js, T> {
    fn as_ref(&self) -> &[T] {
        let (len, ptr) = Self::get_raw(&self.0).expect(T::CLASS_NAME);
        unsafe { slice::from_raw_parts(ptr as _, len) }
    }
}

impl<'js, T: TypedArrayItem> AsMut<[T]> for TypedArray<'js, T> {
    fn as_mut(&mut self) -> &mut [T] {
        let (len, ptr) = Self::get_raw(&self.0).expect(T::CLASS_NAME);
        unsafe { slice::from_raw_parts_mut(ptr, len) }
    }
}

impl<'js, T> Deref for TypedArray<'js, T> {
    type Target = Object<'js>;

    fn deref(&self) -> &Self::Target {
        self.as_object()
    }
}

impl<'js, T> AsRef<Object<'js>> for TypedArray<'js, T> {
    fn as_ref(&self) -> &Object<'js> {
        self.as_object()
    }
}

impl<'js, T> AsRef<Value<'js>> for TypedArray<'js, T> {
    fn as_ref(&self) -> &Value<'js> {
        self.as_value()
    }
}

impl<'js, T> TryFrom<TypedArray<'js, T>> for ArrayBuffer<'js> {
    type Error = Error;

    fn try_from(ta: TypedArray<'js, T>) -> Result<Self> {
        ta.arraybuffer()
    }
}

impl<'js, T> TryFrom<ArrayBuffer<'js>> for TypedArray<'js, T>
where
    T: TypedArrayItem,
{
    type Error = Error;

    fn try_from(ab: ArrayBuffer<'js>) -> Result<Self> {
        Self::from_arraybuffer(ab)
    }
}

impl<'js, T> FromJs<'js> for TypedArray<'js, T>
where
    T: TypedArrayItem,
{
    fn from_js(_: Ctx<'js>, value: Value<'js>) -> Result<Self> {
        Self::from_value(value)
    }
}

impl<'js, T> IntoJs<'js> for TypedArray<'js, T> {
    fn into_js(self, _: Ctx<'js>) -> Result<Value<'js>> {
        Ok(self.into_value())
    }
}

#[cfg(test)]
mod test {
    use crate::*;

    #[test]
    fn from_javascript_i8() {
        test_with(|ctx| {
            let val: TypedArray<i8> = ctx
                .eval(
                    r#"
                        new Int8Array([0, -5, 1, 11])
                    "#,
                )
                .unwrap();
            assert_eq!(val.len(), 4);
            assert_eq!(val.as_ref() as &[i8], &[0i8, -5, 1, 11]);
        });
    }

    #[test]
    fn into_javascript_i8() {
        test_with(|ctx| {
            let val = TypedArray::<i8>::new(ctx, [-1i8, 0, 22, 5]).unwrap();
            ctx.globals().set("v", val).unwrap();
            let res: i8 = ctx
                .eval(
                    r#"
                        v.length != 4 ? 1 :
                        v[0] != -1 ? 2 :
                        v[1] != 0 ? 3 :
                        v[2] != 22 ? 4 :
                        v[3] != 5 ? 5 :
                        0
                    "#,
                )
                .unwrap();
            assert_eq!(res, 0);
        })
    }

    #[test]
    fn from_javascript_f32() {
        test_with(|ctx| {
            let val: TypedArray<f32> = ctx
                .eval(
                    r#"
                        new Float32Array([0.5, -5.25, 123.125])
                    "#,
                )
                .unwrap();
            assert_eq!(val.len(), 3);
            assert_eq!(val.as_ref() as &[f32], &[0.5, -5.25, 123.125]);
        });
    }

    #[test]
    fn into_javascript_f32() {
        test_with(|ctx| {
            let val = TypedArray::<f32>::new(ctx, [-1.5, 0.0, 2.25]).unwrap();
            ctx.globals().set("v", val).unwrap();
            let res: i8 = ctx
                .eval(
                    r#"
                        v.length != 3 ? 1 :
                        v[0] != -1.5 ? 2 :
                        v[1] != 0 ? 3 :
                        v[2] != 2.25 ? 4 :
                        0
                    "#,
                )
                .unwrap();
            assert_eq!(res, 0);
        })
    }
}