summaryrefslogtreecommitdiff
path: root/std/io/iotest.ts
diff options
context:
space:
mode:
authorRyan Dahl <ry@tinyclouds.org>2019-10-09 17:18:08 -0400
committerRyan Dahl <ry@tinyclouds.org>2019-10-09 17:18:08 -0400
commit28293acd9c12a94f5d769706291032e844c7b92b (patch)
tree1fec6a3cd8d7c9e8bc9b1486f5c8438eb906a595 /std/io/iotest.ts
parent5c6835efd82c298df99ce71c4a36ca23515333a3 (diff)
parent151ce0266eb4de2c8fc600c81c192a5f791b6169 (diff)
Merge branch 'std_modified' into merge_std3
Diffstat (limited to 'std/io/iotest.ts')
-rw-r--r--std/io/iotest.ts60
1 files changed, 60 insertions, 0 deletions
diff --git a/std/io/iotest.ts b/std/io/iotest.ts
new file mode 100644
index 000000000..8d2cee6e2
--- /dev/null
+++ b/std/io/iotest.ts
@@ -0,0 +1,60 @@
+// Ported to Deno from
+// Copyright 2009 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+type Reader = Deno.Reader;
+
+/** OneByteReader returns a Reader that implements
+ * each non-empty Read by reading one byte from r.
+ */
+export class OneByteReader implements Reader {
+ constructor(readonly r: Reader) {}
+
+ async read(p: Uint8Array): Promise<number | Deno.EOF> {
+ if (p.byteLength === 0) {
+ return 0;
+ }
+ if (!(p instanceof Uint8Array)) {
+ throw Error("expected Uint8Array");
+ }
+ return this.r.read(p.subarray(0, 1));
+ }
+}
+
+/** HalfReader returns a Reader that implements Read
+ * by reading half as many requested bytes from r.
+ */
+export class HalfReader implements Reader {
+ constructor(readonly r: Reader) {}
+
+ async read(p: Uint8Array): Promise<number | Deno.EOF> {
+ if (!(p instanceof Uint8Array)) {
+ throw Error("expected Uint8Array");
+ }
+ const half = Math.floor((p.byteLength + 1) / 2);
+ return this.r.read(p.subarray(0, half));
+ }
+}
+
+export class ErrTimeout extends Error {
+ constructor() {
+ super("timeout");
+ this.name = "ErrTimeout";
+ }
+}
+
+/** TimeoutReader returns ErrTimeout on the second read
+ * with no data. Subsequent calls to read succeed.
+ */
+export class TimeoutReader implements Reader {
+ count = 0;
+ constructor(readonly r: Reader) {}
+
+ async read(p: Uint8Array): Promise<number | Deno.EOF> {
+ this.count++;
+ if (this.count === 2) {
+ throw new ErrTimeout();
+ }
+ return this.r.read(p);
+ }
+}