2020-09-21 08:26:41 -04:00
|
|
|
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.// Ported to Deno from
|
2018-11-07 20:28:01 -05:00
|
|
|
// 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.
|
2019-03-07 19:25:16 -05:00
|
|
|
type Reader = Deno.Reader;
|
2018-11-07 20:28:01 -05:00
|
|
|
|
|
|
|
/** 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) {}
|
|
|
|
|
2020-04-28 12:40:43 -04:00
|
|
|
read(p: Uint8Array): Promise<number | null> {
|
2018-11-07 20:28:01 -05:00
|
|
|
if (p.byteLength === 0) {
|
2020-03-20 09:38:34 -04:00
|
|
|
return Promise.resolve(0);
|
2018-11-07 20:28:01 -05:00
|
|
|
}
|
|
|
|
if (!(p instanceof Uint8Array)) {
|
|
|
|
throw Error("expected Uint8Array");
|
|
|
|
}
|
2020-03-20 09:38:34 -04:00
|
|
|
return Promise.resolve(this.r.read(p.subarray(0, 1)));
|
2018-11-07 20:28:01 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/** 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) {}
|
|
|
|
|
2020-04-28 12:40:43 -04:00
|
|
|
read(p: Uint8Array): Promise<number | null> {
|
2018-11-07 20:28:01 -05:00
|
|
|
if (!(p instanceof Uint8Array)) {
|
|
|
|
throw Error("expected Uint8Array");
|
|
|
|
}
|
|
|
|
const half = Math.floor((p.byteLength + 1) / 2);
|
2020-03-20 09:38:34 -04:00
|
|
|
return Promise.resolve(this.r.read(p.subarray(0, half)));
|
2018-11-07 20:28:01 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-03-13 21:40:13 -04:00
|
|
|
/** TimeoutReader returns `Deno.errors.TimedOut` on the second read
|
2018-11-07 20:28:01 -05:00
|
|
|
* with no data. Subsequent calls to read succeed.
|
|
|
|
*/
|
|
|
|
export class TimeoutReader implements Reader {
|
|
|
|
count = 0;
|
|
|
|
constructor(readonly r: Reader) {}
|
|
|
|
|
2020-04-28 12:40:43 -04:00
|
|
|
read(p: Uint8Array): Promise<number | null> {
|
2018-11-07 20:28:01 -05:00
|
|
|
this.count++;
|
|
|
|
if (this.count === 2) {
|
2020-03-13 21:40:13 -04:00
|
|
|
throw new Deno.errors.TimedOut();
|
2018-11-07 20:28:01 -05:00
|
|
|
}
|
2020-03-20 09:38:34 -04:00
|
|
|
return Promise.resolve(this.r.read(p));
|
2018-11-07 20:28:01 -05:00
|
|
|
}
|
|
|
|
}
|