Skip to content

Commit

Permalink
Add JS_GetUint8Array API
Browse files Browse the repository at this point in the history
Shorthand for getting the underlying buffer of a Uint8Array.
  • Loading branch information
saghul committed Nov 1, 2023
1 parent b11a104 commit 6d7fd42
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
30 changes: 29 additions & 1 deletion quickjs.c
Expand Up @@ -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)
{
Expand Down
1 change: 1 addition & 0 deletions quickjs.h
Expand Up @@ -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,
Expand Down

0 comments on commit 6d7fd42

Please sign in to comment.