Skip to content

Commit

Permalink
Fix: allow reading into a 0-length array (denoland#3329)
Browse files Browse the repository at this point in the history
  • Loading branch information
qexk authored and ry committed Dec 28, 2019
1 parent 954a0c6 commit 4d4908d
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 1 deletion.
6 changes: 6 additions & 0 deletions cli/js/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand All @@ -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<number | EOF> {
if (p.length == 0) {
return 0;
}
const nread = await sendAsyncMinimal(dispatch.OP_READ, rid, p);
if (nread < 0) {
throw new Error("read error");
Expand Down
4 changes: 4 additions & 0 deletions cli/js/files_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
4 changes: 3 additions & 1 deletion cli/js/io.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down

0 comments on commit 4d4908d

Please sign in to comment.