forked from rvagg/cborg
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbyte-utils.js
More file actions
322 lines (301 loc) · 8.4 KB
/
Copy pathbyte-utils.js
File metadata and controls
322 lines (301 loc) · 8.4 KB
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
// Use Uint8Array directly in the browser, use Buffer in Node.js but don't
// speak its name directly to avoid bundlers pulling in the `Buffer` polyfill
// @ts-ignore
export const useBuffer = globalThis.process &&
// @ts-ignore
!globalThis.process.browser &&
// @ts-ignore
globalThis.Buffer &&
// @ts-ignore
typeof globalThis.Buffer.isBuffer === 'function'
const textEncoder = new TextEncoder()
/**
* @param {Uint8Array} buf
* @returns {boolean}
*/
function isBuffer (buf) {
// @ts-ignore
return useBuffer && globalThis.Buffer.isBuffer(buf)
}
/**
* @param {Uint8Array|number[]} buf
* @returns {Uint8Array<ArrayBuffer>}
*/
export function asU8A (buf) {
if (!(buf instanceof Uint8Array)) {
return Uint8Array.from(buf)
}
const output = isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf
if (isArrayBufferBacked(output)) {
return output
}
return output.slice()
}
/**
*
* @param {Uint8Array} arr
* @returns {arr is Uint8Array<ArrayBuffer>}
*/
function isArrayBufferBacked (arr) {
return arr.buffer instanceof ArrayBuffer
}
// Threshold for manual UTF-8 encoding vs native methods.
// Node.js Buffer.from: crossover ~24 chars
// Browser TextEncoder: crossover ~200 chars
const FROM_STRING_THRESHOLD_BUFFER = 24
const FROM_STRING_THRESHOLD_TEXTENCODER = 200
export const fromString = useBuffer
? // eslint-disable-line operator-linebreak
/**
* @param {string} string
*/
(string) => {
return string.length >= FROM_STRING_THRESHOLD_BUFFER
? // eslint-disable-line operator-linebreak
// @ts-ignore
globalThis.Buffer.from(string)
: utf8ToBytes(string)
}
: // eslint-disable-line operator-linebreak
/**
* @param {string} string
*/
(string) => {
return string.length >= FROM_STRING_THRESHOLD_TEXTENCODER ? textEncoder.encode(string) : utf8ToBytes(string)
}
/**
* Buffer variant not fast enough for what we need
* @param {number[]} arr
* @returns {Uint8Array<ArrayBuffer>}
*/
export const fromArray = (arr) => {
return Uint8Array.from(arr)
}
export const slice = useBuffer
? // eslint-disable-line operator-linebreak
/**
* @param {Uint8Array} bytes
* @param {number} start
* @param {number} end
*/
// Buffer.slice() returns a view, not a copy, so we need special handling
(bytes, start, end) => {
if (isBuffer(bytes)) {
return new Uint8Array(bytes.subarray(start, end))
}
return bytes.slice(start, end)
}
: // eslint-disable-line operator-linebreak
/**
* @param {Uint8Array} bytes
* @param {number} start
* @param {number} end
*/
(bytes, start, end) => {
return bytes.slice(start, end)
}
export const concat = useBuffer
? // eslint-disable-line operator-linebreak
/**
* @param {Uint8Array[]} chunks
* @param {number} length
* @returns {Uint8Array<ArrayBuffer>}
*/
(chunks, length) => {
// might get a stray plain Array here
chunks = chunks.map((c) => c instanceof Uint8Array
? c
: // eslint-disable-line operator-linebreak
// @ts-ignore
globalThis.Buffer.from(c))
// @ts-ignore
return asU8A(globalThis.Buffer.concat(chunks, length))
}
: // eslint-disable-line operator-linebreak
/**
* @param {Uint8Array[]} chunks
* @param {number} length
* @returns {Uint8Array<ArrayBuffer>}
*/
(chunks, length) => {
const out = new Uint8Array(length)
let off = 0
for (let b of chunks) {
if (off + b.length > out.length) {
// final chunk that's bigger than we need
b = b.subarray(0, out.length - off)
}
out.set(b, off)
off += b.length
}
return out
}
export const alloc = useBuffer
? // eslint-disable-line operator-linebreak
/**
* @param {number} size
* @returns {Uint8Array<ArrayBuffer>}
*/
(size) => {
// we always write over the contents we expose so this should be safe
// @ts-ignore
return globalThis.Buffer.allocUnsafe(size)
}
: // eslint-disable-line operator-linebreak
/**
* @param {number} size
* @returns {Uint8Array<ArrayBuffer>}
*/
(size) => {
return new Uint8Array(size)
}
export const toHex = useBuffer
? // eslint-disable-line operator-linebreak
/**
* @param {Uint8Array} d
* @returns {string}
*/
(d) => {
if (typeof d === 'string') {
return d
}
// @ts-ignore
return globalThis.Buffer.from(toBytes(d)).toString('hex')
}
: // eslint-disable-line operator-linebreak
/**
* @param {Uint8Array} d
* @returns {string}
*/
(d) => {
if (typeof d === 'string') {
return d
}
// @ts-ignore not smart enough to figure this out
return Array.prototype.reduce.call(toBytes(d), (p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '')
}
export const fromHex = useBuffer
? // eslint-disable-line operator-linebreak
/**
* @param {string|Uint8Array<ArrayBuffer>} hex
* @returns {Uint8Array<ArrayBuffer>}
*/
(hex) => {
if (hex instanceof Uint8Array) {
return hex
}
// @ts-ignore
return globalThis.Buffer.from(hex, 'hex')
}
: // eslint-disable-line operator-linebreak
/**
* @param {string|Uint8Array<ArrayBuffer>} hex
* @returns {Uint8Array<ArrayBuffer>}
*/
(hex) => {
if (hex instanceof Uint8Array) {
return hex
}
if (!hex.length) {
return new Uint8Array(0)
}
return new Uint8Array(hex.split('')
.map((/** @type {string} */ c, /** @type {number} */ i, /** @type {string[]} */ d) => i % 2 === 0 ? `0x${c}${d[i + 1]}` : '')
.filter(Boolean)
.map((/** @type {string} */ e) => parseInt(e, 16)))
}
/**
* @param {Uint8Array<ArrayBuffer>|ArrayBuffer|ArrayBufferView<ArrayBuffer>} obj
* @returns {Uint8Array<ArrayBuffer>}
*/
function toBytes (obj) {
if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {
return obj
}
if (obj instanceof ArrayBuffer) {
return new Uint8Array(obj)
}
if (ArrayBuffer.isView(obj)) {
return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)
}
throw new Error('Unknown type, must be binary type')
}
/**
* @param {Uint8Array} b1
* @param {Uint8Array} b2
* @returns {number}
*/
export function compare (b1, b2) {
if (isBuffer(b1) && isBuffer(b2)) {
// probably not possible to get here in the current API
// @ts-ignore Buffer
return b1.compare(b2)
}
for (let i = 0; i < b1.length; i++) {
if (b1[i] === b2[i]) {
continue
}
return b1[i] < b2[i] ? -1 : 1
}
return 0
}
// The below code is taken from https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
// Licensed Apache-2.0.
/**
* @param {string} str
* @returns {number[]}
*/
function utf8ToBytes (str) {
const out = []
let p = 0
for (let i = 0; i < str.length; i++) {
let c = str.charCodeAt(i)
if (c < 128) {
out[p++] = c
} else if (c < 2048) {
out[p++] = (c >> 6) | 192
out[p++] = (c & 63) | 128
} else if (
((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&
((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {
// Surrogate Pair
c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF)
out[p++] = (c >> 18) | 240
out[p++] = ((c >> 12) & 63) | 128
out[p++] = ((c >> 6) & 63) | 128
out[p++] = (c & 63) | 128
} else {
if ((c >= 0xD800) && (c <= 0xDFFF)) {
c = 0xFFFD // Unpaired Surrogate
}
out[p++] = (c >> 12) | 224
out[p++] = ((c >> 6) & 63) | 128
out[p++] = (c & 63) | 128
}
}
return out
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
const MAX_ARGUMENTS_LENGTH = 0x1000
/**
* @param {number[]} codePoints
* @returns {string}
*/
export function decodeCodePointsArray (codePoints) {
const len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
let res = ''
let i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}