Add APIs to build a Uint8Array from binary data directly
This commit is contained in:
parent
268cde8270
commit
8f2993bd68
2 changed files with 44 additions and 0 deletions
40
quickjs.c
40
quickjs.c
|
@ -49807,6 +49807,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
|
||||
|
||||
|
|
|
@ -779,6 +779,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);
|
||||
|
|
Loading…
Reference in a new issue