From 4d4908dde31316462acae5caec8dfcbbf7a244bd Mon Sep 17 00:00:00 2001 From: Alexandre Szymocha Date: Sat, 28 Dec 2019 14:48:36 +0100 Subject: [PATCH] Fix: allow reading into a 0-length array (#3329) --- cli/js/files.ts | 6 ++++++ cli/js/files_test.ts | 4 ++++ cli/js/io.ts | 4 +++- 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/cli/js/files.ts b/cli/js/files.ts index 66a70f9812..d3a4b58097 100644 --- a/cli/js/files.ts +++ b/cli/js/files.ts @@ -50,6 +50,9 @@ export async function open( * */ export function readSync(rid: number, p: Uint8Array): number | EOF { + if (p.length == 0) { + return 0; + } const nread = sendSyncMinimal(dispatch.OP_READ, rid, p); if (nread < 0) { throw new Error("read error"); @@ -70,6 +73,9 @@ export function readSync(rid: number, p: Uint8Array): number | EOF { * const text = new TextDecoder().decode(buf); */ export async function read(rid: number, p: Uint8Array): Promise { + if (p.length == 0) { + return 0; + } const nread = await sendAsyncMinimal(dispatch.OP_READ, rid, p); if (nread < 0) { throw new Error("read error"); diff --git a/cli/js/files_test.ts b/cli/js/files_test.ts index 2eaa3b9be1..cb33f69474 100644 --- a/cli/js/files_test.ts +++ b/cli/js/files_test.ts @@ -118,6 +118,10 @@ testPerm( const filename = tempDir + "hello.txt"; const file = await Deno.open(filename, "w+"); + // reading into an empty buffer should return 0 immediately + const bytesRead = await file.read(new Uint8Array(0)); + assert(bytesRead === 0); + // reading file into null buffer should throw an error let err; try { diff --git a/cli/js/io.ts b/cli/js/io.ts index 15a4ad09ba..4ca5289d13 100644 --- a/cli/js/io.ts +++ b/cli/js/io.ts @@ -18,12 +18,14 @@ export enum SeekMode { // https://golang.org/pkg/io/#Reader export interface Reader { /** Reads up to p.byteLength bytes into `p`. It resolves to the number - * of bytes read (`0` < `n` <= `p.byteLength`) and rejects if any error encountered. + * of bytes read (`0` <= `n` <= `p.byteLength`) and rejects if any error encountered. * Even if `read()` returns `n` < `p.byteLength`, it may use all of `p` as * scratch space during the call. If some data is available but not * `p.byteLength` bytes, `read()` conventionally returns what is available * instead of waiting for more. * + * When `p.byteLength` == `0`, `read()` returns `0` and has no other effects. + * * When `read()` encounters end-of-file condition, it returns EOF symbol. * * When `read()` encounters an error, it rejects with an error.