-
Notifications
You must be signed in to change notification settings - Fork 918
/
Copy pathmisc.ts
146 lines (131 loc) · 4.37 KB
/
misc.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
/**
* @license
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { randomBytes } from '../platform/random_bytes';
import { newTextEncoder } from '../platform/text_serializer';
import { debugAssert } from './assert';
export type EventHandler<E> = (value: E) => void;
export interface Indexable {
[k: string]: unknown;
}
/**
* A utility class for generating unique alphanumeric IDs of a specified length.
*
* @internal
* Exported internally for testing purposes.
*/
export class AutoId {
static newId(): string {
// Alphanumeric characters
const chars =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
// The largest byte value that is a multiple of `char.length`.
const maxMultiple = Math.floor(256 / chars.length) * chars.length;
debugAssert(
0 < maxMultiple && maxMultiple < 256,
`Expect maxMultiple to be (0, 256), but got ${maxMultiple}`
);
let autoId = '';
const targetLength = 20;
while (autoId.length < targetLength) {
const bytes = randomBytes(40);
for (let i = 0; i < bytes.length; ++i) {
// Only accept values that are [0, maxMultiple), this ensures they can
// be evenly mapped to indices of `chars` via a modulo operation.
if (autoId.length < targetLength && bytes[i] < maxMultiple) {
autoId += chars.charAt(bytes[i] % chars.length);
}
}
}
debugAssert(autoId.length === targetLength, 'Invalid auto ID: ' + autoId);
return autoId;
}
}
export function primitiveComparator<T>(left: T, right: T): number {
if (left < right) {
return -1;
}
if (left > right) {
return 1;
}
return 0;
}
export interface Equatable<T> {
isEqual(other: T): boolean;
}
/** Compare strings in UTF-8 encoded byte order */
export function compareUtf8Strings(left: string, right: string): number {
for (let i = 0; i < left.length && i < right.length; i++) {
const leftCodePoint = left.codePointAt(i)!;
const rightCodePoint = right.codePointAt(i)!;
if (leftCodePoint !== rightCodePoint) {
if (leftCodePoint < 128 && rightCodePoint < 128) {
// ASCII comparison
return primitiveComparator(leftCodePoint, rightCodePoint);
} else {
// Lazy instantiate TextEncoder
const encoder = newTextEncoder();
// Substring and do UTF-8 encoded byte comparison
const leftBytes = encoder.encode(getUtf8SafeSubstring(left, i));
const rightBytes = encoder.encode(getUtf8SafeSubstring(right, i));
for (
let j = 0;
j < Math.min(leftBytes.length, rightBytes.length);
j++
) {
const comp = primitiveComparator(leftBytes[j], rightBytes[j]);
if (comp !== 0) {
return comp;
}
}
}
}
}
// Compare lengths if all characters are equal
return primitiveComparator(left.length, right.length);
}
function getUtf8SafeSubstring(str: string, index: number): string {
const firstCodePoint = str.codePointAt(index)!;
if (firstCodePoint > 0xffff) {
// It's a surrogate pair, return the whole pair
return str.substring(index, index + 2);
} else {
// It's a single code point, return it
return str.substring(index, index + 1);
}
}
export interface Iterable<V> {
forEach: (cb: (v: V) => void) => void;
}
/** Helper to compare arrays using isEqual(). */
export function arrayEquals<T>(
left: T[],
right: T[],
comparator: (l: T, r: T) => boolean
): boolean {
if (left.length !== right.length) {
return false;
}
return left.every((value, index) => comparator(value, right[index]));
}
/**
* Returns the immediate lexicographically-following string. This is useful to
* construct an inclusive range for indexeddb iterators.
*/
export function immediateSuccessor(s: string): string {
// Return the input string, with an additional NUL byte appended.
return s + '\0';
}