diff --git a/docs/docs/stdlib.md b/docs/docs/stdlib.md index 1cb447ecb..d6bac8415 100644 --- a/docs/docs/stdlib.md +++ b/docs/docs/stdlib.md @@ -538,11 +538,16 @@ position `position` (wrapper to the libc `fwrite`). Return the next line from the file, assuming UTF-8 encoding, excluding the trailing line feed. +#### `readAsArrayBuffer(max_size = undefined)` + +Read `max_size` bytes from the file and return them as an ArrayBuffer. +If `max_size` is not present, the file is read until its end. + #### `readAsString(max_size = undefined)` Read `max_size` bytes from the file and return them as a string assuming UTF-8 encoding. If `max_size` is not present, the file -is read up its end. +is read until its end. #### `getByte()` diff --git a/quickjs-libc.c b/quickjs-libc.c index b96b30669..f62b216cd 100644 --- a/quickjs-libc.c +++ b/quickjs-libc.c @@ -1365,8 +1365,8 @@ static JSValue js_std_file_getline(JSContext *ctx, JSValue this_val, } /* XXX: could use less memory and go faster */ -static JSValue js_std_file_readAsString(JSContext *ctx, JSValue this_val, - int argc, JSValue *argv) +static JSValue js_std_file_readAs(JSContext *ctx, JSValue this_val, + int argc, JSValue *argv, int magic) { FILE *f = js_std_file_get(ctx, this_val); int c; @@ -1402,7 +1402,11 @@ static JSValue js_std_file_readAsString(JSContext *ctx, JSValue this_val, } max_size--; } - obj = JS_NewStringLen(ctx, (const char *)dbuf.buf, dbuf.size); + if (magic) { + obj = JS_NewStringLen(ctx, (const char *)dbuf.buf, dbuf.size); + } else { + obj = JS_NewArrayBufferCopy(ctx, dbuf.buf, dbuf.size); + } dbuf_free(&dbuf); return obj; } @@ -1694,7 +1698,8 @@ static const JSCFunctionListEntry js_std_file_proto_funcs[] = { JS_CFUNC_MAGIC_DEF("read", 3, js_std_file_read_write, 0 ), JS_CFUNC_MAGIC_DEF("write", 3, js_std_file_read_write, 1 ), JS_CFUNC_DEF("getline", 0, js_std_file_getline ), - JS_CFUNC_DEF("readAsString", 0, js_std_file_readAsString ), + JS_CFUNC_MAGIC_DEF("readAsArrayBuffer", 0, js_std_file_readAs, 0 ), + JS_CFUNC_MAGIC_DEF("readAsString", 0, js_std_file_readAs, 1 ), JS_CFUNC_DEF("getByte", 0, js_std_file_getByte ), JS_CFUNC_DEF("putByte", 1, js_std_file_putByte ), /* setvbuf, ... */ diff --git a/tests/test_std.js b/tests/test_std.js index 4603590af..efbbd36f8 100644 --- a/tests/test_std.js +++ b/tests/test_std.js @@ -19,12 +19,16 @@ function test_printf() function test_file1() { - var f, len, str, size, buf, ret, i, str1; + var f, len, str, size, buf, ret, i, str1, ab; f = std.tmpfile(); str = "hello world\n"; f.puts(str); + f.seek(0, std.SEEK_SET); + ab = f.readAsArrayBuffer(); + assert([...new Uint8Array(ab)], str.split("").map(c => c.charCodeAt(0))); + f.seek(0, std.SEEK_SET); str1 = f.readAsString(); assert(str1, str);