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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
use std::{marker::PhantomData, slice};

use crate::{
    context::{internal::Env, Context},
    handle::{internal::TransparentNoCopyWrapper, Handle},
    object::Object,
    result::{JsResult, Throw},
    sys::{self, raw, TypedArrayType},
    types_impl::{
        buffer::{
            lock::{Ledger, Lock},
            private::{self, JsTypedArrayInner},
            BorrowError, Ref, RefMut, Region, TypedArray,
        },
        private::ValueInternal,
        Value,
    },
};

#[cfg(feature = "doc-comment")]
use doc_comment::doc_comment;

#[cfg(not(feature = "doc-comment"))]
macro_rules! doc_comment {
    {$comment:expr, $decl:item} => { $decl };
}

/// The type of Node
/// [`Buffer`](https://nodejs.org/api/buffer.html)
/// objects.
///
/// # Example
///
/// ```
/// # use neon::prelude::*;
/// use neon::types::buffer::TypedArray;
///
/// fn make_sequence(mut cx: FunctionContext) -> JsResult<JsBuffer> {
///     let len = cx.argument::<JsNumber>(0)?.value(&mut cx);
///     let mut buffer = cx.buffer(len as usize)?;
///
///     for (i, elem) in buffer.as_mut_slice(&mut cx).iter_mut().enumerate() {
///         *elem = i as u8;
///     }
///
///     Ok(buffer)
/// }
/// ```
#[derive(Debug)]
#[repr(transparent)]
pub struct JsBuffer(raw::Local);

impl JsBuffer {
    /// Constructs a new `Buffer` object, safely zero-filled.
    ///
    /// **See also:** [`Context::buffer`]
    pub fn new<'a, C: Context<'a>>(cx: &mut C, len: usize) -> JsResult<'a, Self> {
        unsafe {
            let result = sys::buffer::new(cx.env().to_raw(), len);

            if let Ok(buf) = result {
                Ok(Handle::new_internal(Self(buf)))
            } else {
                Err(Throw::new())
            }
        }
    }

    /// Constructs a `JsBuffer` from a slice by copying its contents.
    ///
    /// This method is defined on `JsBuffer` as a convenience and delegates to
    /// [`TypedArray::from_slice`][TypedArray::from_slice].
    pub fn from_slice<'cx, C>(cx: &mut C, slice: &[u8]) -> JsResult<'cx, Self>
    where
        C: Context<'cx>,
    {
        <JsBuffer as TypedArray>::from_slice(cx, slice)
    }

    /// Constructs a new `Buffer` object with uninitialized memory
    pub unsafe fn uninitialized<'a, C: Context<'a>>(cx: &mut C, len: usize) -> JsResult<'a, Self> {
        let result = sys::buffer::uninitialized(cx.env().to_raw(), len);

        if let Ok((buf, _)) = result {
            Ok(Handle::new_internal(Self(buf)))
        } else {
            Err(Throw::new())
        }
    }

    #[cfg(feature = "external-buffers")]
    #[cfg_attr(docsrs, doc(cfg(feature = "external-buffers")))]
    /// Construct a new `Buffer` from bytes allocated by Rust.
    ///
    /// # Compatibility Note
    ///
    /// Some Node environments are built using V8's _sandboxed pointers_ functionality, which
    /// [disallows the use of external buffers](https://www.electronjs.org/blog/v8-memory-cage).
    /// In those environments, calling the underlying
    /// [runtime function](https://nodejs.org/api/n-api.html#napi_create_external_buffer)
    /// used by this method results in an immediate termination of the Node VM.
    ///
    /// As a result, this API is disabled by default. If you are confident that your code will
    /// only be used in environments that disable sandboxed pointers, you can make use of this
    /// method by enabling the **`external-buffers`** feature flag.
    pub fn external<'a, C, T>(cx: &mut C, data: T) -> Handle<'a, Self>
    where
        C: Context<'a>,
        T: AsMut<[u8]> + Send + 'static,
    {
        let env = cx.env().to_raw();
        let value = unsafe { sys::buffer::new_external(env, data) };

        Handle::new_internal(Self(value))
    }
}

unsafe impl TransparentNoCopyWrapper for JsBuffer {
    type Inner = raw::Local;

    fn into_inner(self) -> Self::Inner {
        self.0
    }
}

impl ValueInternal for JsBuffer {
    fn name() -> &'static str {
        "Buffer"
    }

    fn is_typeof<Other: Value>(env: Env, other: &Other) -> bool {
        unsafe { sys::tag::is_buffer(env.to_raw(), other.to_local()) }
    }

    fn to_local(&self) -> raw::Local {
        self.0
    }

    unsafe fn from_local(_env: Env, h: raw::Local) -> Self {
        Self(h)
    }
}

impl Value for JsBuffer {}

impl Object for JsBuffer {}

impl private::Sealed for JsBuffer {}

impl TypedArray for JsBuffer {
    type Item = u8;

    fn as_slice<'cx, 'a, C>(&self, cx: &'a C) -> &'a [Self::Item]
    where
        C: Context<'cx>,
    {
        // # Safety
        // Only the `Context` with the *most* narrow scope is accessible because `compute_scoped`
        // and `execute_scope` take an exclusive reference to `Context`. A handle is always
        // associated with a `Context` and the value will not be garbage collected while that
        // `Context` is in scope. This means that the referenced data is valid *at least* as long
        // as `Context`, even if the `Handle` is dropped.
        unsafe { sys::buffer::as_mut_slice(cx.env().to_raw(), self.to_local()) }
    }

    fn as_mut_slice<'cx, 'a, C>(&mut self, cx: &'a mut C) -> &'a mut [Self::Item]
    where
        C: Context<'cx>,
    {
        // # Safety
        // See `as_slice`
        unsafe { sys::buffer::as_mut_slice(cx.env().to_raw(), self.to_local()) }
    }

    fn try_borrow<'cx, 'a, C>(&self, lock: &'a Lock<C>) -> Result<Ref<'a, Self::Item>, BorrowError>
    where
        C: Context<'cx>,
    {
        // The borrowed data must be guarded by `Ledger` before returning
        Ledger::try_borrow(&lock.ledger, unsafe {
            sys::buffer::as_mut_slice(lock.cx.env().to_raw(), self.to_local())
        })
    }

    fn try_borrow_mut<'cx, 'a, C>(
        &mut self,
        lock: &'a Lock<C>,
    ) -> Result<RefMut<'a, Self::Item>, BorrowError>
    where
        C: Context<'cx>,
    {
        // The borrowed data must be guarded by `Ledger` before returning
        Ledger::try_borrow_mut(&lock.ledger, unsafe {
            sys::buffer::as_mut_slice(lock.cx.env().to_raw(), self.to_local())
        })
    }

    fn size<'cx, C: Context<'cx>>(&self, cx: &mut C) -> usize {
        unsafe { sys::buffer::size(cx.env().to_raw(), self.to_local()) }
    }

    fn from_slice<'cx, C>(cx: &mut C, slice: &[u8]) -> JsResult<'cx, Self>
    where
        C: Context<'cx>,
    {
        let mut buffer = cx.buffer(slice.len())?;
        let target = buffer.as_mut_slice(cx);
        target.copy_from_slice(slice);
        Ok(buffer)
    }
}

/// The type of JavaScript
/// [`ArrayBuffer`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)
/// objects.
///
/// # Example
///
/// ```
/// # use neon::prelude::*;
/// use neon::types::buffer::TypedArray;
///
/// fn make_sequence(mut cx: FunctionContext) -> JsResult<JsArrayBuffer> {
///     let len = cx.argument::<JsNumber>(0)?.value(&mut cx);
///     let mut buffer = cx.array_buffer(len as usize)?;
///
///     for (i, elem) in buffer.as_mut_slice(&mut cx).iter_mut().enumerate() {
///         *elem = i as u8;
///     }
///
///     Ok(buffer)
/// }
/// ```
#[derive(Debug)]
#[repr(transparent)]
pub struct JsArrayBuffer(raw::Local);

impl JsArrayBuffer {
    /// Constructs a new `JsArrayBuffer` object, safely zero-filled.
    ///
    /// **See also:** [`Context::array_buffer`]
    pub fn new<'a, C: Context<'a>>(cx: &mut C, len: usize) -> JsResult<'a, Self> {
        unsafe {
            let result = sys::arraybuffer::new(cx.env().to_raw(), len);

            if let Ok(buf) = result {
                Ok(Handle::new_internal(Self(buf)))
            } else {
                Err(Throw::new())
            }
        }
    }

    /// Constructs a `JsArrayBuffer` from a slice by copying its contents.
    ///
    /// This method is defined on `JsArrayBuffer` as a convenience and delegates to
    /// [`TypedArray::from_slice`][TypedArray::from_slice].
    pub fn from_slice<'cx, C>(cx: &mut C, slice: &[u8]) -> JsResult<'cx, Self>
    where
        C: Context<'cx>,
    {
        <JsArrayBuffer as TypedArray>::from_slice(cx, slice)
    }

    #[cfg(feature = "external-buffers")]
    #[cfg_attr(docsrs, doc(cfg(feature = "external-buffers")))]
    /// Construct a new `JsArrayBuffer` from bytes allocated by Rust.
    ///
    /// # Compatibility Note
    ///
    /// Some Node environments are built using V8's _sandboxed pointers_ functionality, which
    /// [disallows the use of external buffers](https://www.electronjs.org/blog/v8-memory-cage).
    /// In those environments, calling the underlying
    /// [runtime function](https://nodejs.org/api/n-api.html#napi_create_external_arraybuffer)
    /// used by this method results in an immediate termination of the Node VM.
    ///
    /// As a result, this API is disabled by default. If you are confident that your code will
    /// only be used in environments that disable sandboxed pointers, you can make use of this
    /// method by enabling the **`external-buffers`** feature flag.
    pub fn external<'a, C, T>(cx: &mut C, data: T) -> Handle<'a, Self>
    where
        C: Context<'a>,
        T: AsMut<[u8]> + Send + 'static,
    {
        let env = cx.env().to_raw();
        let value = unsafe { sys::arraybuffer::new_external(env, data) };

        Handle::new_internal(Self(value))
    }

    /// Returns a region of this buffer.
    ///
    /// See also: [`Handle<JsArrayBuffer>::region()`](Handle::region) for a more
    /// ergonomic form of this method.
    pub fn region<'cx, T: Binary>(
        buffer: &Handle<'cx, JsArrayBuffer>,
        offset: usize,
        len: usize,
    ) -> Region<'cx, T> {
        buffer.region(offset, len)
    }
}

impl<'cx> Handle<'cx, JsArrayBuffer> {
    /// Returns a [`Region`] representing a typed
    /// region of this buffer, starting at `offset` and containing `len` elements
    /// of type `T`.
    ///
    /// The region is **not** checked for validity by this method. Regions are only
    /// validated when they are converted to typed arrays.
    ///
    /// # Example
    ///
    /// ```
    /// # use neon::prelude::*;
    /// # fn f(mut cx: FunctionContext) -> JsResult<JsUndefined> {
    /// let buf: Handle<JsArrayBuffer> = cx.argument(0)?;
    /// let region = buf.region::<u32>(64, 8);
    /// println!("offset={}, len={}, size={}", region.offset(), region.len(), region.size());
    /// # Ok(cx.undefined())
    /// # }
    /// ```
    ///
    /// See the [`Region`] documentation for more information.
    pub fn region<T: Binary>(&self, offset: usize, len: usize) -> Region<'cx, T> {
        Region {
            buffer: *self,
            offset,
            len,
            phantom: PhantomData,
        }
    }
}

unsafe impl TransparentNoCopyWrapper for JsArrayBuffer {
    type Inner = raw::Local;

    fn into_inner(self) -> Self::Inner {
        self.0
    }
}

impl ValueInternal for JsArrayBuffer {
    fn name() -> &'static str {
        "JsArrayBuffer"
    }

    fn is_typeof<Other: Value>(env: Env, other: &Other) -> bool {
        unsafe { sys::tag::is_arraybuffer(env.to_raw(), other.to_local()) }
    }

    fn to_local(&self) -> raw::Local {
        self.0
    }

    unsafe fn from_local(_env: Env, h: raw::Local) -> Self {
        Self(h)
    }
}

impl Value for JsArrayBuffer {}

impl Object for JsArrayBuffer {}

impl private::Sealed for JsArrayBuffer {}

impl TypedArray for JsArrayBuffer {
    type Item = u8;

    fn as_slice<'cx, 'a, C>(&self, cx: &'a C) -> &'a [Self::Item]
    where
        C: Context<'cx>,
    {
        unsafe { sys::arraybuffer::as_mut_slice(cx.env().to_raw(), self.to_local()) }
    }

    fn as_mut_slice<'cx, 'a, C>(&mut self, cx: &'a mut C) -> &'a mut [Self::Item]
    where
        C: Context<'cx>,
    {
        unsafe { sys::arraybuffer::as_mut_slice(cx.env().to_raw(), self.to_local()) }
    }

    fn try_borrow<'cx, 'a, C>(&self, lock: &'a Lock<C>) -> Result<Ref<'a, Self::Item>, BorrowError>
    where
        C: Context<'cx>,
    {
        // The borrowed data must be guarded by `Ledger` before returning
        Ledger::try_borrow(&lock.ledger, unsafe {
            sys::arraybuffer::as_mut_slice(lock.cx.env().to_raw(), self.to_local())
        })
    }

    fn try_borrow_mut<'cx, 'a, C>(
        &mut self,
        lock: &'a Lock<C>,
    ) -> Result<RefMut<'a, Self::Item>, BorrowError>
    where
        C: Context<'cx>,
    {
        // The borrowed data must be guarded by `Ledger` before returning
        Ledger::try_borrow_mut(&lock.ledger, unsafe {
            sys::arraybuffer::as_mut_slice(lock.cx.env().to_raw(), self.to_local())
        })
    }

    fn size<'cx, C: Context<'cx>>(&self, cx: &mut C) -> usize {
        unsafe { sys::arraybuffer::size(cx.env().to_raw(), self.to_local()) }
    }

    fn from_slice<'cx, C>(cx: &mut C, slice: &[u8]) -> JsResult<'cx, Self>
    where
        C: Context<'cx>,
    {
        let len = slice.len();
        let mut buffer = JsArrayBuffer::new(cx, len)?;
        let target = buffer.as_mut_slice(cx);
        target.copy_from_slice(slice);
        Ok(buffer)
    }
}

/// A marker trait for all possible element types of binary buffers.
///
/// This trait can only be implemented within the Neon library.
pub trait Binary: private::Sealed + Copy {
    /// The internal Node-API enum value for this binary type.
    const TYPE_TAG: TypedArrayType;
}

/// The family of JavaScript [typed array][typed-arrays] types.
///
/// ## Typed Arrays
///
/// JavaScript's [typed arrays][typed-arrays] are objects that allow efficiently reading
/// and writing raw binary data in memory. In Neon, the generic type `JsTypedArray<T>`
/// represents a JavaScript typed array with element type `T`. For example, a JavaScript
/// [`Uint32Array`][Uint32Array] represents a compact array of 32-bit unsigned integers,
/// and is represented in Neon as a `JsTypedArray<u32>`.
///
/// Neon also offers a set of convenience shorthands for concrete instances of
/// `JsTypedArray`, named after their corresponding JavaScript type. For example,
/// `JsTypedArray<u32>` can also be referred to as [`JsUint32Array`][JsUint32Array].
///
/// The following table shows the complete set of typed array types, with both their
/// JavaScript and Neon types:
///
/// | Rust Type                      | Convenience Type                       | JavaScript Type                    |
/// | ------------------------------ | -------------------------------------- | ---------------------------------- |
/// | `JsTypedArray<`[`u8`][u8]`>`   | [`JsUint8Array`][JsUint8Array]         | [`Uint8Array`][Uint8Array]         |
/// | `JsTypedArray<`[`i8`][i8]`>`   | [`JsInt8Array`][JsInt8Array]           | [`Int8Array`][Int8Array]           |
/// | `JsTypedArray<`[`u16`][u16]`>` | [`JsUint16Array`][JsUint16Array]       | [`Uint16Array`][Uint16Array]       |
/// | `JsTypedArray<`[`i16`][i16]`>` | [`JsInt16Array`][JsInt16Array]         | [`Int16Array`][Int16Array]         |
/// | `JsTypedArray<`[`u32`][u32]`>` | [`JsUint32Array`][JsUint32Array]       | [`Uint32Array`][Uint32Array]       |
/// | `JsTypedArray<`[`i32`][i32]`>` | [`JsInt32Array`][JsInt32Array]         | [`Int32Array`][Int32Array]         |
/// | `JsTypedArray<`[`u64`][u64]`>` | [`JsBigUint64Array`][JsBigUint64Array] | [`BigUint64Array`][BigUint64Array] |
/// | `JsTypedArray<`[`i64`][i64]`>` | [`JsBigInt64Array`][JsBigInt64Array]   | [`BigInt64Array`][BigInt64Array]   |
/// | `JsTypedArray<`[`f32`][f32]`>` | [`JsFloat32Array`][JsFloat32Array]     | [`Float32Array`][Float32Array]     |
/// | `JsTypedArray<`[`f64`][f64]`>` | [`JsFloat64Array`][JsFloat64Array]     | [`Float64Array`][Float64Array]     |
///
/// ### Example: Creating an integer array
///
/// This example creates a typed array of unsigned 32-bit integers with a user-specified
/// length:
///
/// ```
/// # use neon::prelude::*;
/// fn create_int_array(mut cx: FunctionContext) -> JsResult<JsTypedArray<u32>> {
///     let len = cx.argument::<JsNumber>(0)?.value(&mut cx) as usize;
///     JsTypedArray::new(&mut cx, len)
/// }
/// ```
///
/// ## Buffers
///
/// Typed arrays are managed with the [`ArrayBuffer`][ArrayBuffer] type, which controls
/// the storage of the underlying data buffer, and several typed views for managing access
/// to the buffer. Neon provides access to the `ArrayBuffer` class with the
/// [`JsArrayBuffer`](crate::types::JsArrayBuffer) type.
///
/// Node also provides a [`Buffer`][Buffer] type, which is built on top of `ArrayBuffer`
/// and provides additional functionality. Neon provides access to the `Buffer` class
/// with the [`JsBuffer`](crate::types::JsBuffer) type.
///
/// Many of Node's I/O APIs work with these types, and they can also be used for
/// compact in-memory data structures, which can be shared efficiently between
/// JavaScript and Rust without copying.
///
/// [u8]: std::primitive::u8
/// [i8]: std::primitive::i8
/// [u16]: std::primitive::u16
/// [i16]: std::primitive::i16
/// [u32]: std::primitive::u32
/// [i32]: std::primitive::i32
/// [u64]: std::primitive::u64
/// [i64]: std::primitive::i64
/// [f32]: std::primitive::f32
/// [f64]: std::primitive::f64
/// [JsUint8Array]: crate::types::JsUint8Array
/// [JsInt8Array]: crate::types::JsInt8Array
/// [JsUint16Array]: crate::types::JsUint16Array
/// [JsInt16Array]: crate::types::JsInt16Array
/// [JsUint32Array]: crate::types::JsUint32Array
/// [JsInt32Array]: crate::types::JsInt32Array
/// [JsBigUint64Array]: crate::types::JsBigUint64Array
/// [JsBigInt64Array]: crate::types::JsBigInt64Array
/// [JsFloat32Array]: crate::types::JsFloat32Array
/// [JsFloat64Array]: crate::types::JsFloat64Array
/// [Uint8Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array
/// [Int8Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array
/// [Uint16Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array
/// [Int16Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array
/// [Uint32Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array
/// [Int32Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array
/// [BigUint64Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigUint64Array
/// [BigInt64Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt64Array
/// [Float32Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array
/// [Float64Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array
/// [typed-arrays]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays
/// [ArrayBuffer]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
/// [Buffer]: https://nodejs.org/api/buffer.html
#[derive(Debug)]
#[repr(transparent)]
pub struct JsTypedArray<T: Binary>(JsTypedArrayInner<T>);

impl<T: Binary> private::Sealed for JsTypedArray<T> {}

unsafe impl<T: Binary> TransparentNoCopyWrapper for JsTypedArray<T> {
    type Inner = JsTypedArrayInner<T>;

    fn into_inner(self) -> Self::Inner {
        self.0
    }
}

impl<T> TypedArray for JsTypedArray<T>
where
    T: Binary,
    Self: Value,
{
    type Item = T;

    fn as_slice<'cx, 'a, C>(&self, cx: &'a C) -> &'a [Self::Item]
    where
        C: Context<'cx>,
    {
        unsafe {
            let env = cx.env().to_raw();
            let value = self.to_local();
            let info = sys::typedarray::info(env, value);

            slice::from_raw_parts(info.data.cast(), info.length)
        }
    }

    fn as_mut_slice<'cx, 'a, C>(&mut self, cx: &'a mut C) -> &'a mut [Self::Item]
    where
        C: Context<'cx>,
    {
        unsafe {
            let env = cx.env().to_raw();
            let value = self.to_local();
            let info = sys::typedarray::info(env, value);

            slice::from_raw_parts_mut(info.data.cast(), info.length)
        }
    }

    fn try_borrow<'cx, 'b, C>(
        &self,
        lock: &'b Lock<'b, C>,
    ) -> Result<Ref<'b, Self::Item>, BorrowError>
    where
        C: Context<'cx>,
    {
        unsafe {
            let env = lock.cx.env().to_raw();
            let value = self.to_local();
            let info = sys::typedarray::info(env, value);

            // The borrowed data must be guarded by `Ledger` before returning
            Ledger::try_borrow(
                &lock.ledger,
                slice::from_raw_parts(info.data.cast(), info.length),
            )
        }
    }

    fn try_borrow_mut<'cx, 'a, C>(
        &mut self,
        lock: &'a Lock<'a, C>,
    ) -> Result<RefMut<'a, Self::Item>, BorrowError>
    where
        C: Context<'cx>,
    {
        unsafe {
            let env = lock.cx.env().to_raw();
            let value = self.to_local();
            let info = sys::typedarray::info(env, value);

            // The borrowed data must be guarded by `Ledger` before returning
            Ledger::try_borrow_mut(
                &lock.ledger,
                slice::from_raw_parts_mut(info.data.cast(), info.length),
            )
        }
    }

    fn size<'cx, C: Context<'cx>>(&self, cx: &mut C) -> usize {
        self.len(cx) * std::mem::size_of::<Self::Item>()
    }

    fn from_slice<'cx, C>(cx: &mut C, slice: &[T]) -> JsResult<'cx, Self>
    where
        C: Context<'cx>,
    {
        let _elt_size = std::mem::size_of::<T>();
        let size = std::mem::size_of_val(slice);
        let buffer = cx.array_buffer(size)?;

        let mut array = Self::from_buffer(cx, buffer)?;
        let target = array.as_mut_slice(cx);
        target.copy_from_slice(slice);

        Ok(array)
    }
}

impl<T: Binary> JsTypedArray<T>
where
    JsTypedArray<T>: Value,
{
    /// Constructs an instance from a slice by copying its contents.
    ///
    /// This method is defined on `JsTypedArray` as a convenience and delegates to
    /// [`TypedArray::from_slice`][TypedArray::from_slice].
    pub fn from_slice<'cx, C>(cx: &mut C, slice: &[T]) -> JsResult<'cx, Self>
    where
        C: Context<'cx>,
    {
        <JsTypedArray<T> as TypedArray>::from_slice(cx, slice)
    }
}

impl<T> JsTypedArray<T>
where
    T: Binary,
    Self: Value,
{
    /// Constructs a typed array that views `buffer`.
    ///
    /// The resulting typed array has `(buffer.size() / size_of::<T>())` elements.
    pub fn from_buffer<'cx, 'b: 'cx, C>(
        cx: &mut C,
        buffer: Handle<'b, JsArrayBuffer>,
    ) -> JsResult<'cx, Self>
    where
        C: Context<'cx>,
    {
        let size = buffer.size(cx);
        let elt_size = std::mem::size_of::<T>();
        let len = size / elt_size;

        if (len * elt_size) != size {
            return cx.throw_range_error(format!(
                "byte length of typed array should be a multiple of {}",
                elt_size
            ));
        }

        Self::from_region(cx, &buffer.region(0, len))
    }

    /// Constructs a typed array for the specified buffer region.
    ///
    /// The resulting typed array has `region.len()` elements and a size of
    /// `region.size()` bytes.
    ///
    /// Throws an exception if the region is invalid, for example if the starting
    /// offset is not properly aligned, or the length goes beyond the end of the
    /// buffer.
    pub fn from_region<'c, 'r, C>(cx: &mut C, region: &Region<'r, T>) -> JsResult<'c, Self>
    where
        C: Context<'c>,
    {
        let &Region {
            buffer,
            offset,
            len,
            ..
        } = region;

        let arr = unsafe {
            sys::typedarray::new(
                cx.env().to_raw(),
                T::TYPE_TAG,
                buffer.to_local(),
                offset,
                len,
            )
            .map_err(|_| Throw::new())?
        };

        Ok(Handle::new_internal(Self(JsTypedArrayInner {
            local: arr,
            buffer: buffer.to_local(),
            _type: PhantomData,
        })))
    }

    /// Returns information about the backing buffer region for this typed array.
    pub fn region<'cx, C>(&self, cx: &mut C) -> Region<'cx, T>
    where
        C: Context<'cx>,
    {
        let env = cx.env();
        let info = unsafe { sys::typedarray::info(env.to_raw(), self.to_local()) };

        Region {
            buffer: Handle::new_internal(unsafe { JsArrayBuffer::from_local(cx.env(), info.buf) }),
            offset: info.offset,
            len: info.length,
            phantom: PhantomData,
        }
    }

    /// Constructs a new typed array of length `len`.
    ///
    /// The resulting typed array has a newly allocated storage buffer of
    /// size `(len * size_of::<T>())` bytes.
    pub fn new<'cx, C>(cx: &mut C, len: usize) -> JsResult<'cx, Self>
    where
        C: Context<'cx>,
    {
        let buffer = cx.array_buffer(len * std::mem::size_of::<T>())?;
        Self::from_region(cx, &buffer.region(0, len))
    }

    /// Returns the [`JsArrayBuffer`](JsArrayBuffer) that owns the underlying storage buffer
    /// for this typed array.
    ///
    /// Note that the typed array might only reference a region of the buffer; use the
    /// [`offset()`](JsTypedArray::offset) and
    /// [`size()`](crate::types::buffer::TypedArray::size) methods to
    /// determine the region.
    pub fn buffer<'cx, C>(&self, cx: &mut C) -> Handle<'cx, JsArrayBuffer>
    where
        C: Context<'cx>,
    {
        Handle::new_internal(unsafe { JsArrayBuffer::from_local(cx.env(), self.0.buffer) })
    }

    /// Returns the offset (in bytes) of the typed array from the start of its
    /// [`JsArrayBuffer`](JsArrayBuffer).
    pub fn offset<'cx, C>(&self, cx: &mut C) -> usize
    where
        C: Context<'cx>,
    {
        let info = unsafe { sys::typedarray::info(cx.env().to_raw(), self.to_local()) };
        info.offset
    }

    /// Returns the length of the typed array, i.e. the number of elements.
    ///
    /// Note that, depending on the element size, this is not necessarily the same as
    /// [`size()`](crate::types::buffer::TypedArray::size). In particular:
    ///
    /// ```ignore
    /// self.size() == self.len() * size_of::<T>()
    /// ```
    #[allow(clippy::len_without_is_empty)]
    pub fn len<'cx, C>(&self, cx: &mut C) -> usize
    where
        C: Context<'cx>,
    {
        let info = unsafe { sys::typedarray::info(cx.env().to_raw(), self.to_local()) };
        info.length
    }
}

macro_rules! impl_typed_array {
    ($typ:ident, $etyp:ty, $($pattern:pat_param)|+, $tag:ident, $alias:ident, $two:expr$(,)?) => {
        impl private::Sealed for $etyp {}

        impl Binary for $etyp {
            const TYPE_TAG: TypedArrayType = TypedArrayType::$tag;
        }

        impl Value for JsTypedArray<$etyp> {}

        impl Object for JsTypedArray<$etyp> {}

        impl ValueInternal for JsTypedArray<$etyp> {
            fn name() -> &'static str {
                stringify!($typ)
            }

            fn is_typeof<Other: Value>(env: Env, other: &Other) -> bool {
                let env = env.to_raw();
                let other = other.to_local();

                if unsafe { !sys::tag::is_typedarray(env, other) } {
                    return false;
                }

                let info = unsafe { sys::typedarray::info(env, other) };

                matches!(info.typ, $($pattern)|+)
            }

            fn to_local(&self) -> raw::Local {
                self.0.local
            }

            unsafe fn from_local(env: Env, local: raw::Local) -> Self {
                // Safety: Recomputing this information ensures that the lifetime of the
                //         buffer handle matches the lifetime of the typed array handle.
                let info = unsafe { sys::typedarray::info(env.to_raw(), local) };

                Self(JsTypedArrayInner {
                    local,
                    buffer: info.buf,
                    _type: PhantomData,
                })
            }
        }

        doc_comment! {
            concat!(
                "The type of JavaScript [`",
                stringify!($typ),
                "`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/",
                stringify!($typ),
                ") objects.

# Example

```
# use neon::prelude::*;
use neon::types::buffer::TypedArray;

fn double(mut cx: FunctionContext) -> JsResult<JsUndefined> {
    let mut array: Handle<",
                stringify!($alias),
                "> = cx.argument(0)?;

    for elem in array.as_mut_slice(&mut cx).iter_mut() {
        *elem *= ",
                stringify!($two),
                ";
    }

    Ok(cx.undefined())
}
```",
            ),
            pub type $alias = JsTypedArray<$etyp>;
        }
    };
}

impl_typed_array!(Int8Array, i8, TypedArrayType::I8, I8, JsInt8Array, 2);
impl_typed_array!(
    Uint8Array,
    u8,
    TypedArrayType::U8 | TypedArrayType::U8Clamped,
    U8,
    JsUint8Array,
    2,
);
impl_typed_array!(Int16Array, i16, TypedArrayType::I16, I16, JsInt16Array, 2);
impl_typed_array!(Uint16Array, u16, TypedArrayType::U16, U16, JsUint16Array, 2);
impl_typed_array!(Int32Array, i32, TypedArrayType::I32, I32, JsInt32Array, 2);
impl_typed_array!(Uint32Array, u32, TypedArrayType::U32, U32, JsUint32Array, 2);
impl_typed_array!(
    Float32Array,
    f32,
    TypedArrayType::F32,
    F32,
    JsFloat32Array,
    2.0,
);
impl_typed_array!(
    Float64Array,
    f64,
    TypedArrayType::F64,
    F64,
    JsFloat64Array,
    2.0,
);
impl_typed_array!(
    BigInt64Array,
    i64,
    TypedArrayType::I64,
    I64,
    JsBigInt64Array,
    2,
);
impl_typed_array!(
    BigUint64Array,
    u64,
    TypedArrayType::U64,
    U64,
    JsBigUint64Array,
    2,
);