2018-05-28 21:50:44 -04:00
|
|
|
// Copyright 2018 Ryan Dahl <ry@tinyclouds.org>
|
|
|
|
// All rights reserved. MIT License.
|
2018-05-19 05:38:51 -04:00
|
|
|
import { debug } from "./main";
|
2018-05-21 18:53:53 -04:00
|
|
|
import { TypedArray } from "./types";
|
2018-05-14 18:22:39 -04:00
|
|
|
|
|
|
|
// Internal logging for deno. Use the "debug" variable above to control
|
|
|
|
// output.
|
|
|
|
// tslint:disable-next-line:no-any
|
|
|
|
export function log(...args: any[]): void {
|
|
|
|
if (debug) {
|
|
|
|
console.log(...args);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-05-14 13:02:47 -04:00
|
|
|
export function assert(cond: boolean, msg = "") {
|
|
|
|
if (!cond) {
|
2018-06-10 19:31:24 -04:00
|
|
|
throw Error(`Assert fail. ${msg}`);
|
2018-05-14 13:02:47 -04:00
|
|
|
}
|
|
|
|
}
|
2018-05-21 18:53:53 -04:00
|
|
|
|
|
|
|
export function typedArrayToArrayBuffer(ta: TypedArray): ArrayBuffer {
|
|
|
|
const ab = ta.buffer.slice(ta.byteOffset, ta.byteOffset + ta.byteLength);
|
|
|
|
return ab as ArrayBuffer;
|
|
|
|
}
|
2018-05-27 03:46:18 -04:00
|
|
|
|
2018-06-01 04:52:30 -04:00
|
|
|
export function arrayToStr(ui8: Uint8Array): string {
|
|
|
|
return String.fromCharCode(...ui8);
|
|
|
|
}
|
|
|
|
|
2018-05-27 03:46:18 -04:00
|
|
|
// A `Resolvable` is a Promise with the `reject` and `resolve` functions
|
|
|
|
// placed as methods on the promise object itself. It allows you to do:
|
|
|
|
//
|
|
|
|
// const p = createResolvable<number>();
|
|
|
|
// ...
|
|
|
|
// p.resolve(42);
|
|
|
|
//
|
|
|
|
// It'd be prettier to make Resolvable a class that inherits from Promise,
|
|
|
|
// rather than an interface. This is possible in ES2016, however typescript
|
|
|
|
// produces broken code when targeting ES5 code.
|
|
|
|
// See https://github.com/Microsoft/TypeScript/issues/15202
|
|
|
|
// At the time of writing, the github issue is closed but the problem remains.
|
|
|
|
export interface Resolvable<T> extends Promise<T> {
|
|
|
|
resolve: (value?: T | PromiseLike<T>) => void;
|
|
|
|
// tslint:disable-next-line:no-any
|
|
|
|
reject: (reason?: any) => void;
|
|
|
|
}
|
|
|
|
export function createResolvable<T>(): Resolvable<T> {
|
|
|
|
let methods;
|
|
|
|
const promise = new Promise<T>((resolve, reject) => {
|
|
|
|
methods = { resolve, reject };
|
|
|
|
});
|
|
|
|
return Object.assign(promise, methods) as Resolvable<T>;
|
|
|
|
}
|