Skip to content

Add APIs to build a Uint8Array from binary data directly #126

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions quickjs.c
Original file line number Diff line number Diff line change
Expand Up @@ -49798,6 +49798,46 @@ static const JSCFunctionListEntry js_dataview_proto_funcs[] = {
JS_PROP_STRING_DEF("[Symbol.toStringTag]", "DataView", JS_PROP_CONFIGURABLE ),
};

static JSValue js_new_uint8array(JSContext *ctx, JSValue buffer)
{
if (JS_IsException(buffer))
return JS_EXCEPTION;
JSValue obj = js_create_from_ctor(ctx, JS_UNDEFINED, JS_CLASS_UINT8_ARRAY);
if (JS_IsException(obj)) {
JS_FreeValue(ctx, buffer);
return JS_EXCEPTION;
}
JSArrayBuffer *abuf = JS_GetOpaque(buffer, JS_CLASS_ARRAY_BUFFER);
assert(abuf != NULL);
if (typed_array_init(ctx, obj, buffer, 0, abuf->byte_length)) {
// 'buffer' is freed on error above.
JS_FreeValue(ctx, obj);
return JS_EXCEPTION;
}
return obj;
}

JSValue JS_NewUint8Array(JSContext *ctx, uint8_t *buf, size_t len,
JSFreeArrayBufferDataFunc *free_func, void *opaque,
JS_BOOL is_shared)
{
JSValue buffer = js_array_buffer_constructor3(ctx, JS_UNDEFINED, len,
is_shared ? JS_CLASS_SHARED_ARRAY_BUFFER : JS_CLASS_ARRAY_BUFFER,
buf, free_func, opaque, FALSE);
return js_new_uint8array(ctx, buffer);
}

JSValue JS_NewUint8ArrayCopy(JSContext *ctx, const uint8_t *buf, size_t len)
{
JSValue buffer = js_array_buffer_constructor3(ctx, JS_UNDEFINED, len,
JS_CLASS_ARRAY_BUFFER,
(uint8_t *)buf,
js_array_buffer_free, NULL,
TRUE);
return js_new_uint8array(ctx, buffer);
}


/* Atomics */
#ifdef CONFIG_ATOMICS

Expand Down
4 changes: 4 additions & 0 deletions quickjs.h
Original file line number Diff line number Diff line change
Expand Up @@ -777,6 +777,10 @@ JSValue JS_GetTypedArrayBuffer(JSContext *ctx, JSValueConst obj,
size_t *pbyte_offset,
size_t *pbyte_length,
size_t *pbytes_per_element);
JSValue JS_NewUint8Array(JSContext *ctx, uint8_t *buf, size_t len,
JSFreeArrayBufferDataFunc *free_func, void *opaque,
JS_BOOL is_shared);
JSValue JS_NewUint8ArrayCopy(JSContext *ctx, const uint8_t *buf, size_t len);
typedef struct {
void *(*sab_alloc)(void *opaque, size_t size);
void (*sab_free)(void *opaque, void *ptr);
Expand Down