2020-01-02 15:13:47 -05:00
|
|
|
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
2019-03-07 19:25:16 -05:00
|
|
|
type Reader = Deno.Reader;
|
2020-04-01 15:23:39 -04:00
|
|
|
import { encode } from "../encoding/utf8.ts";
|
2019-02-10 18:49:48 -05:00
|
|
|
|
|
|
|
/** Reader utility for strings */
|
|
|
|
export class StringReader implements Reader {
|
|
|
|
private offs = 0;
|
|
|
|
private buf = new Uint8Array(encode(this.s));
|
|
|
|
|
|
|
|
constructor(private readonly s: string) {}
|
|
|
|
|
2020-03-20 09:38:34 -04:00
|
|
|
read(p: Uint8Array): Promise<number | Deno.EOF> {
|
2019-02-10 18:49:48 -05:00
|
|
|
const n = Math.min(p.byteLength, this.buf.byteLength - this.offs);
|
|
|
|
p.set(this.buf.slice(this.offs, this.offs + n));
|
|
|
|
this.offs += n;
|
2019-07-07 15:20:41 -04:00
|
|
|
if (n === 0) {
|
2020-03-20 09:38:34 -04:00
|
|
|
return Promise.resolve(Deno.EOF);
|
2019-07-07 15:20:41 -04:00
|
|
|
}
|
2020-03-20 09:38:34 -04:00
|
|
|
return Promise.resolve(n);
|
2019-02-10 18:49:48 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/** Reader utility for combining multiple readers */
|
|
|
|
export class MultiReader implements Reader {
|
|
|
|
private readonly readers: Reader[];
|
|
|
|
private currentIndex = 0;
|
|
|
|
|
|
|
|
constructor(...readers: Reader[]) {
|
|
|
|
this.readers = readers;
|
|
|
|
}
|
|
|
|
|
2019-07-07 15:20:41 -04:00
|
|
|
async read(p: Uint8Array): Promise<number | Deno.EOF> {
|
2019-02-10 18:49:48 -05:00
|
|
|
const r = this.readers[this.currentIndex];
|
2019-07-07 15:20:41 -04:00
|
|
|
if (!r) return Deno.EOF;
|
|
|
|
const result = await r.read(p);
|
|
|
|
if (result === Deno.EOF) {
|
2019-02-10 18:49:48 -05:00
|
|
|
this.currentIndex++;
|
2019-07-07 15:20:41 -04:00
|
|
|
return 0;
|
2019-02-10 18:49:48 -05:00
|
|
|
}
|
2019-07-07 15:20:41 -04:00
|
|
|
return result;
|
2019-02-10 18:49:48 -05:00
|
|
|
}
|
|
|
|
}
|