From 6d7fd42aae0f835002da964e206fddcf47d6c9e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sa=C3=BAl=20Ibarra=20Corretg=C3=A9?= Date: Wed, 1 Nov 2023 21:31:05 +0100 Subject: [PATCH] Add JS_GetUint8Array API Shorthand for getting the underlying buffer of a Uint8Array. --- quickjs.c | 30 +++++++++++++++++++++++++++++- quickjs.h | 1 + 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/quickjs.c b/quickjs.c index 8bcd1fef..36f65593 100644 --- a/quickjs.c +++ b/quickjs.c @@ -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) { diff --git a/quickjs.h b/quickjs.h index f6745b19..09085209 100644 --- a/quickjs.h +++ b/quickjs.h @@ -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,