Skip to content

Commit 8f2993b

Browse files
committed
Add APIs to build a Uint8Array from binary data directly
1 parent 268cde8 commit 8f2993b

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

quickjs.c

+40
Original file line numberDiff line numberDiff line change
@@ -49807,6 +49807,46 @@ static const JSCFunctionListEntry js_dataview_proto_funcs[] = {
4980749807
JS_PROP_STRING_DEF("[Symbol.toStringTag]", "DataView", JS_PROP_CONFIGURABLE ),
4980849808
};
4980949809

49810+
static JSValue js_new_uint8array(JSContext *ctx, JSValue buffer)
49811+
{
49812+
if (JS_IsException(buffer))
49813+
return JS_EXCEPTION;
49814+
JSValue obj = js_create_from_ctor(ctx, JS_UNDEFINED, JS_CLASS_UINT8_ARRAY);
49815+
if (JS_IsException(obj)) {
49816+
JS_FreeValue(ctx, buffer);
49817+
return JS_EXCEPTION;
49818+
}
49819+
JSArrayBuffer *abuf = JS_GetOpaque(buffer, JS_CLASS_ARRAY_BUFFER);
49820+
assert(abuf != NULL);
49821+
if (typed_array_init(ctx, obj, buffer, 0, abuf->byte_length)) {
49822+
// 'buffer' is freed on error above.
49823+
JS_FreeValue(ctx, obj);
49824+
return JS_EXCEPTION;
49825+
}
49826+
return obj;
49827+
}
49828+
49829+
JSValue JS_NewUint8Array(JSContext *ctx, uint8_t *buf, size_t len,
49830+
JSFreeArrayBufferDataFunc *free_func, void *opaque,
49831+
JS_BOOL is_shared)
49832+
{
49833+
JSValue buffer = js_array_buffer_constructor3(ctx, JS_UNDEFINED, len,
49834+
is_shared ? JS_CLASS_SHARED_ARRAY_BUFFER : JS_CLASS_ARRAY_BUFFER,
49835+
buf, free_func, opaque, FALSE);
49836+
return js_new_uint8array(ctx, buffer);
49837+
}
49838+
49839+
JSValue JS_NewUint8ArrayCopy(JSContext *ctx, const uint8_t *buf, size_t len)
49840+
{
49841+
JSValue buffer = js_array_buffer_constructor3(ctx, JS_UNDEFINED, len,
49842+
JS_CLASS_ARRAY_BUFFER,
49843+
(uint8_t *)buf,
49844+
js_array_buffer_free, NULL,
49845+
TRUE);
49846+
return js_new_uint8array(ctx, buffer);
49847+
}
49848+
49849+
4981049850
/* Atomics */
4981149851
#ifdef CONFIG_ATOMICS
4981249852

quickjs.h

+4
Original file line numberDiff line numberDiff line change
@@ -779,6 +779,10 @@ JSValue JS_GetTypedArrayBuffer(JSContext *ctx, JSValueConst obj,
779779
size_t *pbyte_offset,
780780
size_t *pbyte_length,
781781
size_t *pbytes_per_element);
782+
JSValue JS_NewUint8Array(JSContext *ctx, uint8_t *buf, size_t len,
783+
JSFreeArrayBufferDataFunc *free_func, void *opaque,
784+
JS_BOOL is_shared);
785+
JSValue JS_NewUint8ArrayCopy(JSContext *ctx, const uint8_t *buf, size_t len);
782786
typedef struct {
783787
void *(*sab_alloc)(void *opaque, size_t size);
784788
void (*sab_free)(void *opaque, void *ptr);

0 commit comments

Comments
 (0)