1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-01 09:24:20 -04:00
denoland-deno/cli/js/io.ts
Bartek Iwańczuk b508e84567
refactor: remove combined io interface like ReadCloser (#4944)
This commit removes "combined" interfaces from cli/js/io.ts; in the
like of "ReadCloser", "WriteCloser" in favor of using intersections
of concrete interfaces.
2020-04-28 12:32:43 +02:00

111 lines
2.4 KiB
TypeScript

// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
// Interfaces 100% copied from Go.
// Documentation liberally lifted from them too.
// Thank you! We love Go!
export const EOF: unique symbol = Symbol("EOF");
export type EOF = typeof EOF;
const DEFAULT_BUFFER_SIZE = 32 * 1024;
// Seek whence values.
// https://golang.org/pkg/io/#pkg-constants
export enum SeekMode {
Start = 0,
Current = 1,
End = 2,
}
// Reader is the interface that wraps the basic read() method.
// https://golang.org/pkg/io/#Reader
export interface Reader {
read(p: Uint8Array): Promise<number | EOF>;
}
export interface SyncReader {
readSync(p: Uint8Array): number | EOF;
}
// Writer is the interface that wraps the basic write() method.
// https://golang.org/pkg/io/#Writer
export interface Writer {
write(p: Uint8Array): Promise<number>;
}
export interface SyncWriter {
writeSync(p: Uint8Array): number;
}
// https://golang.org/pkg/io/#Closer
export interface Closer {
// The behavior of Close after the first call is undefined. Specific
// implementations may document their own behavior.
close(): void;
}
// https://golang.org/pkg/io/#Seeker
export interface Seeker {
seek(offset: number, whence: SeekMode): Promise<number>;
}
export interface SyncSeeker {
seekSync(offset: number, whence: SeekMode): number;
}
export async function copy(
src: Reader,
dst: Writer,
options?: {
bufSize?: number;
}
): Promise<number> {
let n = 0;
const bufSize = options?.bufSize ?? DEFAULT_BUFFER_SIZE;
const b = new Uint8Array(bufSize);
let gotEOF = false;
while (gotEOF === false) {
const result = await src.read(b);
if (result === EOF) {
gotEOF = true;
} else {
n += await dst.write(b.subarray(0, result));
}
}
return n;
}
export async function* iter(
r: Reader,
options?: {
bufSize?: number;
}
): AsyncIterableIterator<Uint8Array> {
const bufSize = options?.bufSize ?? DEFAULT_BUFFER_SIZE;
const b = new Uint8Array(bufSize);
while (true) {
const result = await r.read(b);
if (result === EOF) {
break;
}
yield b.subarray(0, result);
}
}
export function* iterSync(
r: SyncReader,
options?: {
bufSize?: number;
}
): IterableIterator<Uint8Array> {
const bufSize = options?.bufSize ?? DEFAULT_BUFFER_SIZE;
const b = new Uint8Array(bufSize);
while (true) {
const result = r.readSync(b);
if (result === EOF) {
break;
}
yield b.subarray(0, result);
}
}