From 90b8087970966581e698e79650cf43e045dd17e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sa=C3=BAl=20Ibarra=20Corretg=C3=A9?= Date: Mon, 25 Sep 2023 23:42:54 +0200 Subject: [PATCH] utils: add helper to create a Uint8Array while copying the data --- src/utils.c | 14 ++++++++++++-- src/utils.h | 3 ++- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/src/utils.c b/src/utils.c index 67b987f4..205b4d12 100644 --- a/src/utils.c +++ b/src/utils.c @@ -1,6 +1,5 @@ - /* - * QuickJS libuv bindings + * txiki.js * * Copyright (c) 2019-present Saúl Ibarra Corretgé * @@ -271,6 +270,17 @@ JSValue TJS_NewUint8Array(JSContext *ctx, uint8_t *data, size_t size) { return buf; } +JSValue TJS_NewUint8ArrayCopy(JSContext *ctx, uint8_t *data, size_t size) { + JSValue abuf = JS_NewArrayBufferCopy(ctx, data, size); + if (JS_IsException(abuf)) + return abuf; + TJSRuntime *qrt = TJS_GetRuntime(ctx); + CHECK_NOT_NULL(qrt); + JSValue buf = JS_CallConstructor(ctx, qrt->builtins.u8array_ctor, 1, &abuf); + JS_FreeValue(ctx, abuf); + return buf; +} + JSValue TJS_NewDate(JSContext *ctx, double epoch_ms) { TJSRuntime *qrt = TJS_GetRuntime(ctx); CHECK_NOT_NULL(qrt); diff --git a/src/utils.h b/src/utils.h index d2639d22..e299a227 100644 --- a/src/utils.h +++ b/src/utils.h @@ -1,5 +1,5 @@ /* - * QuickJS libuv bindings + * txiki.js * * Copyright (c) 2019-present Saúl Ibarra Corretgé * @@ -122,6 +122,7 @@ JSValue TJS_NewResolvedPromise(JSContext *ctx, int argc, JSValueConst *argv); JSValue TJS_NewRejectedPromise(JSContext *ctx, int argc, JSValueConst *argv); JSValue TJS_NewUint8Array(JSContext *ctx, uint8_t *data, size_t size); +JSValue TJS_NewUint8ArrayCopy(JSContext *ctx, uint8_t *data, size_t size); JSValue TJS_NewDate(JSContext *ctx, double epoch_ms); extern const char *tjs_signal_map[];