Add JS_GetUint8Array API

Shorthand for getting the underlying buffer of a Uint8Array.
This commit is contained in:
Saúl Ibarra Corretgé 2023-11-01 21:31:05 +01:00
parent b11a10471d
commit 6d7fd42aae
2 changed files with 30 additions and 1 deletions

View file

@ -51683,7 +51683,35 @@ JSValue JS_GetTypedArrayBuffer(JSContext *ctx, JSValueConst obj,
}
return JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, ta->buffer));
}
/* return NULL if exception. WARNING: any JS call can detach the
buffer and render the returned pointer invalid */
uint8_t *JS_GetUint8Array(JSContext *ctx, size_t *psize, JSValueConst obj)
{
JSObject *p;
JSTypedArray *ta;
JSArrayBuffer *abuf;
p = get_typed_array(ctx, obj, FALSE);
if (!p)
goto fail;
if (typed_array_is_detached(ctx, p)) {
JS_ThrowTypeErrorDetachedArrayBuffer(ctx);
goto fail;
}
if (p->class_id != JS_CLASS_UINT8_ARRAY && p->class_id != JS_CLASS_UINT8C_ARRAY) {
JS_ThrowTypeError(ctx, "not a Uint8Array");
goto fail;
}
ta = p->u.typed_array;
abuf = ta->buffer->u.array_buffer;
*psize = ta->length;
return abuf->data + ta->offset;
fail:
*psize = 0;
return NULL;
}
static JSValue js_typed_array_get_toStringTag(JSContext *ctx,
JSValueConst this_val)
{

View file

@ -818,6 +818,7 @@ JSValue JS_NewArrayBuffer(JSContext *ctx, uint8_t *buf, size_t len,
JSValue JS_NewArrayBufferCopy(JSContext *ctx, const uint8_t *buf, size_t len);
void JS_DetachArrayBuffer(JSContext *ctx, JSValueConst obj);
uint8_t *JS_GetArrayBuffer(JSContext *ctx, size_t *psize, JSValueConst obj);
uint8_t *JS_GetUint8Array(JSContext *ctx, size_t *psize, JSValueConst obj);
JSValue JS_GetTypedArrayBuffer(JSContext *ctx, JSValueConst obj,
size_t *pbyte_offset,
size_t *pbyte_length,