Debian Codegraph @

js/public/experimental/TypedData.h

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 /*
8 * Typed array, ArrayBuffer, and DataView creation, predicate, and accessor
9 * functions.
10 */
11
12 #ifndef js_experimental_TypedData_h
13 #define js_experimental_TypedData_h
14
15 #include "mozilla/Assertions.h" // MOZ_ASSERT, MOZ_CRASH
16 #include "mozilla/Casting.h" // mozilla::AssertedCast
17 #include "mozilla/Span.h"
18
19 #include <stddef.h> // size_t
20 #include <stdint.h> // {,u}int8_t, {,u}int16_t, {,u}int32_t
21
22 #include "jstypes.h" // JS_PUBLIC_API
23
24 #include "js/Object.h" // JS::GetClass, JS::GetReservedSlot, JS::GetMaybePtrFromReservedSlot
25 #include "js/RootingAPI.h" // JS::Handle, JS_DECLARE_IS_HEAP_CONSTRUCTIBLE_TYPE
26 #include "js/ScalarType.h" // JS::Scalar::Type
27 #include "js/Wrapper.h" // js::CheckedUnwrapStatic
28
29 struct JSClass;
30 class JS_PUBLIC_API JSObject;
31
32 namespace JS {
33
34 class JS_PUBLIC_API AutoRequireNoGC;
35
36 } // namespace JS
37
38 // JS_FOR_EACH_TYPED_ARRAY(MACRO) expands MACRO once for each specific
39 // typed array subtype (Int8Array, Float64Array, ...), passing arguments
40 // as MACRO(ExternalT, NativeT, Name) where
41 //
42 // ExternalT - externally-exposed element type (eg uint8_t)
43 //
44 // NativeT - element type used for the implementation (eg js::uint8_clamped_t)
45 // Note that this type is not exposed publicly. Internal files need to
46 // #include <vm/Uint8Clamped.h> to see it.
47 //
48 // Name - a name usable as both a JS::Scalar::Type value (eg
49 // JS::Scalar::Uint8Clamped) or the stem of a full typed array name (eg
50 // Uint8ClampedArray)
51 //
52 #define JS_FOR_EACH_TYPED_ARRAY(MACRO) \
53 MACRO(int8_t, int8_t, Int8) \
54 MACRO(uint8_t, uint8_t, Uint8) \
55 MACRO(int16_t, int16_t, Int16) \
56 MACRO(uint16_t, uint16_t, Uint16) \
57 MACRO(int32_t, int32_t, Int32) \
58 MACRO(uint32_t, uint32_t, Uint32) \
59 MACRO(float, float, Float32) \
60 MACRO(double, double, Float64) \
61 MACRO(uint8_t, js::uint8_clamped, Uint8Clamped) \
62 MACRO(int64_t, int64_t, BigInt64) \
63 MACRO(uint64_t, uint64_t, BigUint64) \
64 MACRO(uint16_t, js::float16, Float16)
65
66 /*
67 * JS_New(type)Array:
68 *
69 * Create a new typed array with nelements elements.
70 *
71 * These functions (except the WithBuffer variants) fill in the array with
72 * zeros.
73 *
74 * JS_New(type)ArrayFromArray:
75 *
76 * Create a new typed array and copy in values from the given object. The
77 * object is used as if it were an array; that is, the new array (if
78 * successfully created) will have length given by array.length, and its
79 * elements will be those specified by array[0], array[1], and so on, after
80 * conversion to the typed array element type.
81 *
82 * JS_New(type)ArrayWithBuffer:
83 *
84 * Create a new typed array using the given ArrayBuffer or
85 * SharedArrayBuffer for storage. The length value is optional; if -1
86 * is passed, enough elements to use up the remainder of the byte
87 * array is used as the default value.
88 */
89
90 #define DECLARE_TYPED_ARRAY_CREATION_API(ExternalType, NativeType, Name) \
91 extern JS_PUBLIC_API JSObject* JS_New##Name##Array(JSContext* cx, \
92 size_t nelements); \
93 extern JS_PUBLIC_API JSObject* JS_New##Name##ArrayFromArray( \
94 JSContext* cx, JS::Handle<JSObject*> array); \
95 extern JS_PUBLIC_API JSObject* JS_New##Name##ArrayWithBuffer( \
96 JSContext* cx, JS::Handle<JSObject*> arrayBuffer, size_t byteOffset, \
97 int64_t length);
98
99 JS_FOR_EACH_TYPED_ARRAY(DECLARE_TYPED_ARRAY_CREATION_API)
100 #undef DECLARE_TYPED_ARRAY_CREATION_API
101
102 /**
103 * Check whether obj supports JS_GetTypedArray* APIs. Note that this may return
104 * false if a security wrapper is encountered that denies the unwrapping. If
105 * this test or one of the JS_Is*Array tests succeeds, then it is safe to call
106 * the various accessor JSAPI calls defined below.
107 */
108 extern JS_PUBLIC_API bool JS_IsTypedArrayObject(JSObject* obj);
109
110 /**
111 * Check whether obj supports JS_GetArrayBufferView* APIs. Note that this may
112 * return false if a security wrapper is encountered that denies the
113 * unwrapping. If this test or one of the more specific tests succeeds, then it
114 * is safe to call the various ArrayBufferView accessor JSAPI calls defined
115 * below.
116 */
117 extern JS_PUBLIC_API bool JS_IsArrayBufferViewObject(JSObject* obj);
118
119 /**
120 * Return the isShared flag of a typed array, which denotes whether
121 * the underlying buffer is a SharedArrayBuffer.
122 *
123 * |obj| must have passed a JS_IsTypedArrayObject/JS_Is*Array test, or somehow
124 * be known that it would pass such a test: it is a typed array or a wrapper of
125 * a typed array, and the unwrapping will succeed.
126 */
127 extern JS_PUBLIC_API bool JS_GetTypedArraySharedness(JSObject* obj);
128
129 /*
130 * Test for specific typed array types (ArrayBufferView subtypes) and return
131 * the unwrapped object if so, else nullptr. Never throws.
132 */
133
134 namespace js {
135
136 extern JS_PUBLIC_API JSObject* UnwrapArrayBufferView(JSObject* obj);
137
138 namespace detail {
139
140 constexpr size_t TypedArrayLengthSlot = 1;
141 constexpr size_t TypedArrayDataSlot = 3;
142
143 } // namespace detail
144
145 // This one isn't inlined because it's rather tricky (by dint of having to deal
146 // with a dozen-plus classes and varying slot layouts.
147 extern JS_PUBLIC_API void GetArrayBufferViewLengthAndData(JSObject* obj,
148 size_t* length,
149 bool* isSharedMemory,
150 uint8_t** data);
151
152 } // namespace js
153
154 /*
155 * JS_GetObjectAs(type)Array(JSObject* maybeWrapped, size_t* length, bool*
156 * isSharedMemory, element_type** data)
157 *
158 * Unwrap Typed arrays all at once. Return nullptr without throwing if the
159 * object cannot be viewed as the correct typed array, or the typed array
160 * object on success, filling both outparameters.
161 */
162 #define DECLARE_GET_OBJECT_AS(ExternalType, NativeType, Name) \
163 extern JS_PUBLIC_API JSObject* JS_GetObjectAs##Name##Array( \
164 JSObject* maybeWrapped, size_t* length, bool* isSharedMemory, \
165 ExternalType** data);
166 JS_FOR_EACH_TYPED_ARRAY(DECLARE_GET_OBJECT_AS)
167 #undef DECLARE_GET_OBJECT_AS
168
169 extern JS_PUBLIC_API JSObject* JS_GetObjectAsArrayBufferView(
170 JSObject* obj, size_t* length, bool* isSharedMemory, uint8_t** data);
171
172 /*
173 * Get the type of elements in a typed array, or MaxTypedArrayViewType if a
174 * DataView.
175 *
176 * |obj| must have passed a JS_IsArrayBufferView/JS_Is*Array test, or somehow
177 * be known that it would pass such a test: it is an ArrayBufferView or a
178 * wrapper of an ArrayBufferView, and the unwrapping will succeed.
179 */
180 extern JS_PUBLIC_API JS::Scalar::Type JS_GetArrayBufferViewType(JSObject* obj);
181
182 /**
183 * Return the number of elements in a typed array.
184 *
185 * |obj| must have passed a JS_IsTypedArrayObject/JS_Is*Array test, or somehow
186 * be known that it would pass such a test: it is a typed array or a wrapper of
187 * a typed array, and the unwrapping will succeed.
188 */
189 extern JS_PUBLIC_API size_t JS_GetTypedArrayLength(JSObject* obj);
190
191 /**
192 * Return the byte offset from the start of an ArrayBuffer to the start of a
193 * typed array view.
194 *
195 * |obj| must have passed a JS_IsTypedArrayObject/JS_Is*Array test, or somehow
196 * be known that it would pass such a test: it is a typed array or a wrapper of
197 * a typed array, and the unwrapping will succeed.
198 */
199 extern JS_PUBLIC_API size_t JS_GetTypedArrayByteOffset(JSObject* obj);
200
201 /**
202 * Return the byte length of a typed array.
203 *
204 * |obj| must have passed a JS_IsTypedArrayObject/JS_Is*Array test, or somehow
205 * be known that it would pass such a test: it is a typed array or a wrapper of
206 * a typed array, and the unwrapping will succeed.
207 */
208 extern JS_PUBLIC_API size_t JS_GetTypedArrayByteLength(JSObject* obj);
209
210 /**
211 * More generic name for JS_GetTypedArrayByteLength to cover DataViews as well
212 */
213 extern JS_PUBLIC_API size_t JS_GetArrayBufferViewByteLength(JSObject* obj);
214
215 /**
216 * More generic name for JS_GetTypedArrayByteOffset to cover DataViews as well
217 */
218 extern JS_PUBLIC_API size_t JS_GetArrayBufferViewByteOffset(JSObject* obj);
219
220 /**
221 * Same as above, but for any kind of ArrayBufferView. Prefer the type-specific
222 * versions when possible.
223 */
224 extern JS_PUBLIC_API void* JS_GetArrayBufferViewData(
225 JSObject* obj, bool* isSharedMemory, const JS::AutoRequireNoGC&);
226
227 /**
228 * Return a "fixed" pointer (one that will not move during a GC) to the
229 * ArrayBufferView's data. Note that this will not keep the object alive; the
230 * holding object should be rooted or traced. If the view is storing the data
231 * inline, this will copy the data to the provided buffer, returning nullptr if
232 * bufSize is inadequate.
233 *
234 * Avoid using this unless necessary. JS_GetArrayBufferViewData is simpler and
235 * more efficient because it requires the caller to ensure that a GC will not
236 * occur and thus does not need to handle movable data.
237 */
238 extern JS_PUBLIC_API uint8_t* JS_GetArrayBufferViewFixedData(JSObject* obj,
239 uint8_t* buffer,
240 size_t bufSize);
241
242 /**
243 * If the bufSize passed to JS_GetArrayBufferViewFixedData is at least this
244 * many bytes, then any copied data is guaranteed to fit into the provided
245 * buffer.
246 */
247 extern JS_PUBLIC_API size_t JS_MaxMovableTypedArraySize();
248
249 /**
250 * Return the ArrayBuffer or SharedArrayBuffer underlying an ArrayBufferView.
251 * This may return a detached buffer. |obj| must be an object that would
252 * return true for JS_IsArrayBufferViewObject().
253 */
254 extern JS_PUBLIC_API JSObject* JS_GetArrayBufferViewBuffer(
255 JSContext* cx, JS::Handle<JSObject*> obj, bool* isSharedMemory);
256
257 /**
258 * Create a new DataView using the given buffer for storage. The given buffer
259 * must be an ArrayBuffer or SharedArrayBuffer (or a cross-compartment wrapper
260 * of either type), and the offset and length must fit within the bounds of the
261 * buffer. Currently, nullptr will be returned and an exception will be thrown
262 * if these conditions do not hold, but do not depend on that behavior.
263 */
264 JS_PUBLIC_API JSObject* JS_NewDataView(JSContext* cx,
265 JS::Handle<JSObject*> buffer,
266 size_t byteOffset, size_t byteLength);
267
268 namespace JS {
269
270 /*
271 * Returns whether the passed array buffer view is 'large': its byteLength >= 2
272 * GB.
273 *
274 * |obj| must pass a JS_IsArrayBufferViewObject test.
275 */
276 JS_PUBLIC_API bool IsLargeArrayBufferView(JSObject* obj);
277
278 /*
279 * Returns whether the passed array buffer view has a resizable or growable
280 * array buffer.
281 *
282 * |obj| must pass a JS_IsArrayBufferViewObject test.
283 */
284 JS_PUBLIC_API bool IsResizableArrayBufferView(JSObject* obj);
285
286 /*
287 * Given an ArrayBuffer or view, prevent the length of the underlying
288 * ArrayBuffer from changing (with pin=true) until unfrozen (with
289 * pin=false). Note that some objects (eg SharedArrayBuffers) cannot change
290 * length to begin with, and are treated as always pinned.
291 *
292 * ArrayBuffers and their views can change length by being detached, or
293 * if they are ResizableArrayBuffers or (shared) GrowableArrayBuffers.
294 *
295 * Returns whether the pinned status changed.
296 */
297 JS_PUBLIC_API bool PinArrayBufferOrViewLength(JSObject* obj, bool pin);
298
299 /*
300 * Given an ArrayBuffer or view, make sure its contents are not stored inline
301 * so that the data is safe for use even if a GC moves the owning object.
302 *
303 * Note that this by itself does not make it safe to use the data pointer
304 * if JS can run or the ArrayBuffer can be detached in any way. Consider using
305 * this in conjunction with PinArrayBufferOrViewLength, which will cause any
306 * potentially invalidating operations to fail.
307 */
308 JS_PUBLIC_API bool EnsureNonInlineArrayBufferOrView(JSContext* cx,
309 JSObject* obj);
310
311 namespace detail {
312
313 // Map from eg Uint8Clamped -> uint8_t, Uint8 -> uint8_t, or Float64 ->
314 // double. Used as the DataType within a JS::TypedArray specialization.
315 template <JS::Scalar::Type ArrayType>
316 struct ExternalTypeOf {};
317
318 #define DEFINE_ELEMENT_TYPES(ExternalT, NativeT, Name) \
319 template <> \
320 struct ExternalTypeOf<JS::Scalar::Name> { \
321 using Type = ExternalT; \
322 };
323 JS_FOR_EACH_TYPED_ARRAY(DEFINE_ELEMENT_TYPES)
324 #undef DEFINE_ELEMENT_TYPES
325
326 template <JS::Scalar::Type ArrayType>
327 using ExternalTypeOf_t = typename ExternalTypeOf<ArrayType>::Type;
328
329 } // namespace detail
330
331 // A class holding a JSObject referring to a buffer of data. Either an
332 // ArrayBufferObject or some sort of ArrayBufferViewObject (see below).
333 // Note that this will always hold an unwrapped object.
334 class JS_PUBLIC_API ArrayBufferOrView {
335 public:
336 // Typed Arrays will set this to their specific element type.
337 // Everything else just claims to expose things as uint8_t*.
338 using DataType = uint8_t;
339
340 protected:
341 JSObject* obj;
342
343 explicit ArrayBufferOrView(JSObject* unwrapped) : obj(unwrapped) {}
344
345 public:
346 // ArrayBufferOrView subclasses will set `obj` to nullptr if wrapping an
347 // object of the wrong type. So this allows:
348 //
349 // auto view = JS::TypedArray<JS::Scalar::Int8>::fromObject(obj);
350 // if (!view) { ... }
351 //
352 explicit operator bool() const { return !!obj; }
353
354 // `obj` must be an unwrapped ArrayBuffer or view, or nullptr.
355 static inline ArrayBufferOrView fromObject(JSObject* unwrapped);
356
357 // Unwrap an ArrayBuffer or view. Returns ArrayBufferOrView(nullptr) if
358 // `maybeWrapped` is the wrong type or fails unwrapping. Never throw.
359 static ArrayBufferOrView unwrap(JSObject* maybeWrapped);
360
361 // Allow use as Rooted<JS::ArrayBufferOrView>.
362 void trace(JSTracer* trc) {
363 if (obj) {
364 js::gc::TraceExternalEdge(trc, &obj, "ArrayBufferOrView object");
365 }
366 }
367
368 bool isDetached() const;
369 bool isResizable() const;
370
371 void exposeToActiveJS() const {
372 if (obj) {
373 js::BarrierMethods<JSObject*>::exposeToJS(obj);
374 }
375 }
376
377 JSObject* asObject() const {
378 exposeToActiveJS();
379 return obj;
380 }
381
382 JSObject* asObjectUnbarriered() const { return obj; }
383
384 JSObject** addressOfObject() { return &obj; }
385
386 bool operator==(const ArrayBufferOrView& other) const {
387 return obj == other.asObjectUnbarriered();
388 }
389 bool operator!=(const ArrayBufferOrView& other) const {
390 return obj != other.asObjectUnbarriered();
391 }
392 };
393
394 class JS_PUBLIC_API ArrayBuffer : public ArrayBufferOrView {
395 static const JSClass* const FixedLengthUnsharedClass;
396 static const JSClass* const ResizableUnsharedClass;
397 static const JSClass* const FixedLengthSharedClass;
398 static const JSClass* const GrowableSharedClass;
399
400 protected:
401 explicit ArrayBuffer(JSObject* unwrapped) : ArrayBufferOrView(unwrapped) {}
402
403 public:
404 static ArrayBuffer fromObject(JSObject* unwrapped) {
405 if (unwrapped) {
406 const JSClass* clasp = GetClass(unwrapped);
407 if (clasp == FixedLengthUnsharedClass ||
408 clasp == ResizableUnsharedClass || clasp == FixedLengthSharedClass ||
409 clasp == GrowableSharedClass) {
410 return ArrayBuffer(unwrapped);
411 }
412 }
413 return ArrayBuffer(nullptr);
414 }
415 static ArrayBuffer unwrap(JSObject* maybeWrapped);
416
417 static ArrayBuffer create(JSContext* cx, size_t nbytes);
418
419 mozilla::Span<uint8_t> getData(bool* isSharedMemory,
420 const JS::AutoRequireNoGC&);
421 };
422
423 // A view into an ArrayBuffer, either a DataViewObject or a Typed Array variant.
424 class JS_PUBLIC_API ArrayBufferView : public ArrayBufferOrView {
425 protected:
426 explicit ArrayBufferView(JSObject* unwrapped)
427 : ArrayBufferOrView(unwrapped) {}
428
429 public:
430 static inline ArrayBufferView fromObject(JSObject* unwrapped);
431 static ArrayBufferView unwrap(JSObject* maybeWrapped) {
432 if (!maybeWrapped) {
433 return ArrayBufferView(nullptr);
434 }
435 ArrayBufferView view = fromObject(maybeWrapped);
436 if (view) {
437 return view;
438 }
439 return fromObject(js::CheckedUnwrapStatic(maybeWrapped));
440 }
441
442 bool isDetached() const;
443 bool isResizable() const;
444
445 mozilla::Span<uint8_t> getData(bool* isSharedMemory,
446 const JS::AutoRequireNoGC&);
447
448 // Must only be called if !isDetached().
449 size_t getByteLength(const JS::AutoRequireNoGC&);
450 };
451
452 class JS_PUBLIC_API DataView : public ArrayBufferView {
453 static const JSClass* const FixedLengthClassPtr;
454 static const JSClass* const ResizableClassPtr;
455
456 protected:
457 explicit DataView(JSObject* unwrapped) : ArrayBufferView(unwrapped) {}
458
459 public:
460 static DataView fromObject(JSObject* unwrapped) {
461 if (unwrapped) {
462 const JSClass* clasp = GetClass(unwrapped);
463 if (clasp == FixedLengthClassPtr || clasp == ResizableClassPtr) {
464 return DataView(unwrapped);
465 }
466 }
467 return DataView(nullptr);
468 }
469
470 static DataView unwrap(JSObject* maybeWrapped) {
471 if (!maybeWrapped) {
472 return DataView(nullptr);
473 }
474 DataView view = fromObject(maybeWrapped);
475 if (view) {
476 return view;
477 }
478 return fromObject(js::CheckedUnwrapStatic(maybeWrapped));
479 }
480 };
481
482 // Base type of all Typed Array variants.
483 class JS_PUBLIC_API TypedArray_base : public ArrayBufferView {
484 protected:
485 explicit TypedArray_base(JSObject* unwrapped) : ArrayBufferView(unwrapped) {}
486
487 static const JSClass* const fixedLengthClasses;
488 static const JSClass* const resizableClasses;
489
490 public:
491 static TypedArray_base fromObject(JSObject* unwrapped);
492
493 static TypedArray_base unwrap(JSObject* maybeWrapped) {
494 if (!maybeWrapped) {
495 return TypedArray_base(nullptr);
496 }
497 TypedArray_base view = fromObject(maybeWrapped);
498 if (view) {
499 return view;
500 }
501 return fromObject(js::CheckedUnwrapStatic(maybeWrapped));
502 }
503 };
504
505 template <JS::Scalar::Type TypedArrayElementType>
506 class JS_PUBLIC_API TypedArray : public TypedArray_base {
507 // This cannot be a static data member because on Windows,
508 // __declspec(dllexport) causes the class to be instantiated immediately,
509 // leading to errors when later explicit specializations of inline member
510 // functions are encountered ("error: explicit specialization of 'ClassPtr'
511 // after instantiation"). And those inlines need to be defined outside of the
512 // class due to order dependencies. This is the only way I could get it to
513 // work on both Windows and POSIX.
514 static const JSClass* fixedLengthClasp() {
515 return &TypedArray_base::fixedLengthClasses[static_cast<int>(
516 TypedArrayElementType)];
517 }
518 static const JSClass* resizableClasp() {
519 return &TypedArray_base::resizableClasses[static_cast<int>(
520 TypedArrayElementType)];
521 }
522
523 protected:
524 explicit TypedArray(JSObject* unwrapped) : TypedArray_base(unwrapped) {}
525
526 public:
527 using DataType = detail::ExternalTypeOf_t<TypedArrayElementType>;
528
529 static constexpr JS::Scalar::Type Scalar = TypedArrayElementType;
530
531 static TypedArray create(JSContext* cx, size_t nelements);
532 static TypedArray fromArray(JSContext* cx, HandleObject other);
533 static TypedArray fromBuffer(JSContext* cx, HandleObject arrayBuffer,
534 size_t byteOffset, int64_t length);
535
536 // Return an interface wrapper around `obj`, or around nullptr if `obj` is not
537 // an unwrapped typed array of the correct type.
538 static TypedArray fromObject(JSObject* unwrapped) {
539 if (unwrapped) {
540 const JSClass* clasp = GetClass(unwrapped);
541 if (clasp == fixedLengthClasp() || clasp == resizableClasp()) {
542 return TypedArray(unwrapped);
543 }
544 }
545 return TypedArray(nullptr);
546 }
547
548 static TypedArray unwrap(JSObject* maybeWrapped) {
549 if (!maybeWrapped) {
550 return TypedArray(nullptr);
551 }
552 TypedArray view = fromObject(maybeWrapped);
553 if (view) {
554 return view;
555 }
556 return fromObject(js::CheckedUnwrapStatic(maybeWrapped));
557 }
558
559 // Return a pointer to the start of the data referenced by a typed array. The
560 // data is still owned by the typed array, and should not be modified on
561 // another thread. Furthermore, the pointer can become invalid on GC (if the
562 // data is small and fits inside the array's GC header), so callers must take
563 // care not to hold on across anything that could GC.
564 //
565 // |obj| must have passed a JS_Is*Array test, or somehow be known that it
566 // would pass such a test: it is a typed array or a wrapper of a typed array,
567 // and the unwrapping will succeed.
568 //
569 // |*isSharedMemory| will be set to true if the typed array maps a
570 // SharedArrayBuffer, otherwise to false.
571 //
572 mozilla::Span<DataType> getData(bool* isSharedMemory,
573 const JS::AutoRequireNoGC& nogc);
574 };
575
576 ArrayBufferOrView ArrayBufferOrView::fromObject(JSObject* unwrapped) {
577 if (ArrayBuffer::fromObject(unwrapped) ||
578 ArrayBufferView::fromObject(unwrapped)) {
579 return ArrayBufferOrView(unwrapped);
580 }
581 return ArrayBufferOrView(nullptr);
582 }
583
584 ArrayBufferView ArrayBufferView::fromObject(JSObject* unwrapped) {
585 if (TypedArray_base::fromObject(unwrapped) ||
586 DataView::fromObject(unwrapped)) {
587 return ArrayBufferView(unwrapped);
588 }
589 return ArrayBufferView(nullptr);
590 }
591
592 } /* namespace JS */
593
594 /*
595 * JS_Get(type)ArrayData(JSObject* obj,
596 * bool* isSharedMemory,
597 * const JS::AutoRequireNoGC&)
598 *
599 * js::Get(type)ArrayLengthAndData(JSObject* obj,
600 * size_t* length,
601 * bool* isSharedMemory,
602 * const JS::AutoRequireNoGC&)
603 *
604 * Return a pointer to the start of the data referenced by a typed array. The
605 * data is still owned by the typed array, and should not be modified on
606 * another thread. Furthermore, the pointer can become invalid on GC (if the
607 * data is small and fits inside the array's GC header), so callers must take
608 * care not to hold on across anything that could GC.
609 *
610 * |obj| must have passed a JS_Is*Array test, or somehow be known that it would
611 * pass such a test: it is a typed array or a wrapper of a typed array, and the
612 * unwrapping will succeed.
613 *
614 * |*isSharedMemory| will be set to true if the typed array maps a
615 * SharedArrayBuffer, otherwise to false.
616 */
617
618 #define JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(ExternalType, NativeType, Name) \
619 extern JS_PUBLIC_API ExternalType* JS_Get##Name##ArrayData( \
620 JSObject* maybeWrapped, bool* isSharedMemory, \
621 const JS::AutoRequireNoGC&); \
622 \
623 namespace js { \
624 inline void Get##Name##ArrayLengthAndData(JSObject* unwrapped, \
625 size_t* length, \
626 bool* isSharedMemory, \
627 ExternalType** data) { \
628 MOZ_ASSERT(JS::TypedArray<JS::Scalar::Name>::fromObject(unwrapped)); \
629 const JS::Value& lenSlot = \
630 JS::GetReservedSlot(unwrapped, detail::TypedArrayLengthSlot); \
631 *length = size_t(lenSlot.toPrivate()); \
632 *isSharedMemory = JS_GetTypedArraySharedness(unwrapped); \
633 *data = JS::GetMaybePtrFromReservedSlot<ExternalType>( \
634 unwrapped, detail::TypedArrayDataSlot); \
635 } \
636 \
637 JS_PUBLIC_API JSObject* Unwrap##Name##Array(JSObject* maybeWrapped); \
638 } /* namespace js */
639
640 JS_FOR_EACH_TYPED_ARRAY(JS_DEFINE_DATA_AND_LENGTH_ACCESSOR)
641 #undef JS_DEFINE_DATA_AND_LENGTH_ACCESSOR
642
643 namespace JS {
644
645 #define IMPL_TYPED_ARRAY_CLASS(ExternalType, NativeType, Name) \
646 template <> \
647 inline JS::TypedArray<JS::Scalar::Name> \
648 JS::TypedArray<JS::Scalar::Name>::create(JSContext* cx, size_t nelements) { \
649 return fromObject(JS_New##Name##Array(cx, nelements)); \
650 }; \
651 \
652 template <> \
653 inline JS::TypedArray<JS::Scalar::Name> \
654 JS::TypedArray<JS::Scalar::Name>::fromArray(JSContext* cx, \
655 HandleObject other) { \
656 return fromObject(JS_New##Name##ArrayFromArray(cx, other)); \
657 }; \
658 \
659 template <> \
660 inline JS::TypedArray<JS::Scalar::Name> \
661 JS::TypedArray<JS::Scalar::Name>::fromBuffer( \
662 JSContext* cx, HandleObject arrayBuffer, size_t byteOffset, \
663 int64_t length) { \
664 return fromObject( \
665 JS_New##Name##ArrayWithBuffer(cx, arrayBuffer, byteOffset, length)); \
666 };
667
668 JS_FOR_EACH_TYPED_ARRAY(IMPL_TYPED_ARRAY_CLASS)
669 #undef IMPL_TYPED_ARRAY_CLASS
670
671 // Create simple names like Int8Array, Float32Array, etc.
672 #define JS_DECLARE_CLASS_ALIAS(ExternalType, NativeType, Name) \
673 using Name##Array = TypedArray<js::Scalar::Name>;
674 JS_FOR_EACH_TYPED_ARRAY(JS_DECLARE_CLASS_ALIAS)
675 #undef JS_DECLARE_CLASS_ALIAS
676
677 } // namespace JS
678
679 namespace js {
680
681 template <typename T>
682 using EnableIfABOVType =
683 std::enable_if_t<std::is_base_of_v<JS::ArrayBufferOrView, T>>;
684
685 template <typename T, typename Wrapper>
686 class WrappedPtrOperations<T, Wrapper, EnableIfABOVType<T>> {
687 auto get() const { return static_cast<const Wrapper*>(this)->get(); }
688
689 public:
690 explicit operator bool() const { return bool(get()); }
691 JSObject* asObject() const { return get().asObject(); }
692 bool isDetached() const { return get().isDetached(); }
693 bool isSharedMemory() const { return get().isSharedMemory(); }
694
695 mozilla::Span<typename T::DataType> getData(bool* isSharedMemory,
696 const JS::AutoRequireNoGC& nogc) {
697 return get().getData(isSharedMemory, nogc);
698 }
699 };
700
701 // Allow usage within Heap<T>.
702 template <typename T>
703 struct IsHeapConstructibleType<T, EnableIfABOVType<T>> : public std::true_type {
704 };
705
706 template <typename T>
707 struct BarrierMethods<T, EnableIfABOVType<T>> {
708 static gc::Cell* asGCThingOrNull(T view) {
709 return reinterpret_cast<gc::Cell*>(view.asObjectUnbarriered());
710 }
711 static void writeBarriers(T* viewp, T prev, T next) {
712 BarrierMethods<JSObject*>::writeBarriers(viewp->addressOfObject(),
713 prev.asObjectUnbarriered(),
714 next.asObjectUnbarriered());
715 }
716 static void postWriteBarrier(T* viewp, T prev, T next) {
717 BarrierMethods<JSObject*>::postWriteBarrier(viewp->addressOfObject(),
718 prev.asObjectUnbarriered(),
719 next.asObjectUnbarriered());
720 }
721 static void exposeToJS(T view) { view.exposeToActiveJS(); }
722 static void readBarrier(T view) {
723 JSObject* obj = view.asObjectUnbarriered();
724 if (obj) {
725 js::gc::IncrementalReadBarrier(JS::GCCellPtr(obj));
726 }
727 }
728 };
729
730 } // namespace js
731
732 namespace JS {
733 template <typename T>
734 struct SafelyInitialized<T, js::EnableIfABOVType<T>> {
735 static T create() { return T::fromObject(nullptr); }
736 };
737 } // namespace JS
738
739 /*
740 * JS_Is(type)Array(JSObject* maybeWrapped)
741 *
742 * Test for specific typed array types.
743 */
744
745 #define DECLARE_IS_ARRAY_TEST(_1, _2, Name) \
746 inline JS_PUBLIC_API bool JS_Is##Name##Array(JSObject* maybeWrapped) { \
747 return JS::TypedArray<js::Scalar::Name>::unwrap(maybeWrapped).asObject(); \
748 }
749 JS_FOR_EACH_TYPED_ARRAY(DECLARE_IS_ARRAY_TEST)
750 #undef DECLARE_IS_ARRAY_TEST
751
752 #endif // js_experimental_TypedData_h