From e749b37b7cc811f32d18e6cc9a8daa5c2f055d00 Mon Sep 17 00:00:00 2001 From: DanSnow Date: Sat, 1 Dec 2018 01:58:31 +0800 Subject: [PATCH] Add deno.readAll() (#1234) --- js/buffer.ts | 8 ++++++++ js/buffer_test.ts | 14 ++++++++++++-- js/deno.ts | 2 +- 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/js/buffer.ts b/js/buffer.ts index b06259ed0d..4e9cd6eb2f 100644 --- a/js/buffer.ts +++ b/js/buffer.ts @@ -221,3 +221,11 @@ export class Buffer implements Reader, Writer { } } } + +/** Read `r` until EOF and return the content as `Uint8Array`. + */ +export async function readAll(r: Reader): Promise { + const buf = new Buffer(); + await buf.readFrom(r); + return buf.bytes(); +} diff --git a/js/buffer_test.ts b/js/buffer_test.ts index 843a85f97d..58668de266 100644 --- a/js/buffer_test.ts +++ b/js/buffer_test.ts @@ -1,8 +1,8 @@ +import { Buffer, readAll } from "deno"; // This code has been ported almost directly from Go's src/bytes/buffer_test.go // Copyright 2009 The Go Authors. All rights reserved. BSD license. // https://github.com/golang/go/blob/master/LICENSE -import { test, assert, assertEqual } from "./test_util.ts"; -import { Buffer } from "deno"; +import { assert, assertEqual, test } from "./test_util.ts"; // N controls how many iterations of certain checks are performed. const N = 100; @@ -193,3 +193,13 @@ test(async function bufferTestGrow() { } } }); + +test(async function testReadAll() { + init(); + const reader = new Buffer(testBytes.buffer as ArrayBuffer); + const actualBytes = await readAll(reader); + assertEqual(testBytes.byteLength, actualBytes.byteLength); + for (let i = 0; i < testBytes.length; ++i) { + assertEqual(testBytes[i], actualBytes[i]); + } +}); diff --git a/js/deno.ts b/js/deno.ts index fc1c099d64..21c93c5d3b 100644 --- a/js/deno.ts +++ b/js/deno.ts @@ -20,7 +20,7 @@ export { ReadWriteCloser, ReadWriteSeeker } from "./io"; -export { Buffer } from "./buffer"; +export { Buffer, readAll } from "./buffer"; export { mkdirSync, mkdir } from "./mkdir"; export { makeTempDirSync, makeTempDir } from "./make_temp_dir"; export { chmodSync, chmod } from "./chmod";