• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright 2022 Google LLC
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/** Promise that completes after the specified `timeMs` */
18export function delay(timeMs: number): Promise<void> {
19  return new Promise<void>((complete) => setTimeout(complete, timeMs));
20}
21
22/**
23 * A `Promise` to be completed
24 */
25export class Deferred<T> extends Promise<T> {
26  readonly resolve: (value: T) => void;
27  readonly reject: (reason?: any) => void;
28
29  constructor() {
30    let capturedResolve: (value: T) => void;
31    let capturedReject: (reason?: any) => void;
32
33    super((resolve, reject) => {
34      capturedResolve = resolve;
35      capturedReject = reject;
36    });
37
38    this.resolve = capturedResolve!;
39    this.reject = capturedReject!;
40  }
41}
42
43export function namedError(name: string, message?: string): Error {
44  const result = new Error(message);
45  result.name = name;
46  return result;
47}
48
49export function isNamedError(e: unknown, name: string): e is Error {
50  return e instanceof Error && e.name === name;
51}
52
53/** Checks whether both `Uint8Array` have the same contents. */
54export function arrayBufferEquals(
55  left: Uint8Array,
56  right: Uint8Array
57): boolean {
58  if (left.byteLength != right.byteLength) return false;
59
60  for (let i = 0; i < left.byteLength; i++) {
61    if (left.at(i) != right.at(i)) return false;
62  }
63
64  return true;
65}
66
67export function asciiStringToBytes(contents: string): Uint8Array {
68  const result = new TextEncoder().encode(contents);
69  if (result.length != contents.length) {
70    // non-ascii characters require multiple bytes in utf-8.
71    throw new Error(`non-ascii characters found in '${contents}'`);
72  }
73  return result;
74}
75