Repository navigation
Expand file tree
/
Copy pathbytes.ts
More file actions
284 lines (276 loc) · 10.5 KB
/
Copy pathbytes.ts
File metadata and controls
284 lines (276 loc) · 10.5 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
import type { Eval } from "../interpreter/runner.js"
import { checkArrayLength, checkStringLength } from "../interpreter/limits.js"
import { constructor, methods, prototypeFrom, receiver, requiresNew } from "../interpreter/native.js"
import { IteratorSymbol, rangeError, syntaxError, typeError } from "../interpreter/model.js"
import {
define,
defineAccessor,
get,
hidden,
Arr,
Bytes,
hostIterator,
Obj,
coerceToInteger,
coerceToNumber,
coerceToString,
type Value,
} from "../interpreter/objects.js"
import { describeValue } from "../interpreter/references.js"
import { applyCollectionCallback } from "../interpreter/callback.js"
import type { Interpreter } from "../interpreter/interpreter.js"
import { callbackMethods, sortArray } from "./array.js"
/**
* The bytes a Uint8Array, array, or other iterable of numbers describes; the host array clamps each value. As in
* TypedArray.from, a mapper sees the original values, after the source is consumed in full.
*/
function* collectBytes<R>(
ctx: Interpreter<R>,
source: Value,
name: string,
mapper?: Value,
thisArg?: Value,
): Eval<Uint8Array> {
const apply = mapper === undefined ? undefined : applyCollectionCallback(ctx, mapper, name)
if (source instanceof Bytes && apply === undefined) return new Uint8Array(source.bytes)
const cursor = yield* ctx.iterate(source)
if (cursor === undefined) {
throw typeError(
`${name} expects a Uint8Array, an array, or an iterable of numbers, received ${describeValue(source)}.`,
)
}
const values: Array<Value> = []
while (true) {
const step = yield* cursor.next()
if (step.done) break
values.push(step.value)
checkArrayLength(values.length)
}
if (apply === undefined) return Uint8Array.from(values, coerceToNumber)
const mapped: Array<Value> = []
for (const [index, value] of values.entries()) mapped.push(yield* apply([value, index], thisArg))
return Uint8Array.from(mapped, coerceToNumber)
}
function* constructBytes<R>(ctx: Interpreter<R>, args: Array<Value>, proto: Obj): Eval<Bytes> {
const source = args[0]
if (source !== null && typeof source === "object") {
return new Bytes(proto, yield* collectBytes(ctx, source, "new Uint8Array(...)"))
}
const length = source === undefined ? 0 : coerceToNumber(source)
if (!Number.isInteger(length) || length < 0) throw rangeError(`Invalid typed array length: ${coerceToString(source)}`)
checkArrayLength(length)
return new Bytes(proto, new Uint8Array(length))
}
export const uint8ArrayGlobal = <R>(ctx: Interpreter<R>) => {
const builtins = ctx.builtins
const proto = builtins.Uint8Array
const wrap = (bytes: Uint8Array) => new Bytes(proto, bytes)
const uint8Array = constructor(builtins, proto, {
name: "Uint8Array",
length: 3,
call: requiresNew("Uint8Array"),
construct: (args, newTarget) => constructBytes(ctx, args, prototypeFrom(newTarget, proto)),
})
const decode = (name: string, args: Array<Value>, from: (text: string) => Uint8Array) => {
if (typeof args[0] !== "string") throw typeError(`Uint8Array.${name} expects a string.`)
try {
return wrap(from(args[0]))
} catch {
throw syntaxError(`Uint8Array.${name}: the string is not valid ${name === "fromHex" ? "hex" : "base64"}.`)
}
}
methods(builtins, uint8Array, [
[
"from",
1,
function* (_, args) {
return wrap(yield* collectBytes(ctx, args[0], "Uint8Array.from", args[1], args[2]))
},
],
["of", 0, (_, args) => wrap(Uint8Array.from(args, coerceToNumber))],
["fromBase64", 1, (_, args) => decode("fromBase64", args, (text) => Uint8Array.fromBase64(text))],
["fromHex", 1, (_, args) => decode("fromHex", args, (text) => Uint8Array.fromHex(text))],
])
const self = (thisValue: Value, name: string) => receiver(Bytes, thisValue, `Uint8Array.prototype.${name}`)
const optNumber = (value: Value): number | undefined => (value === undefined ? undefined : coerceToInteger(value))
// Uint8Array cannot contain NaN, so non-number search values never match a byte.
const search = (value: Value) => (typeof value === "number" ? value : NaN)
const wrapAll = (items: Array<Value>) => new Arr(builtins.Array, items)
defineAccessor(proto, "length", (thisValue) => self(thisValue, "length").bytes.length)
methods(builtins, proto, [
["at", 1, (thisValue, args) => self(thisValue, "at").bytes.at(optNumber(args[0]) ?? 0)],
[
"slice",
2,
(thisValue, args) => wrap(self(thisValue, "slice").bytes.slice(optNumber(args[0]), optNumber(args[1]))),
],
// A view on the same bytes, as in JS: writes through one are visible through the other.
[
"subarray",
2,
(thisValue, args) => wrap(self(thisValue, "subarray").bytes.subarray(optNumber(args[0]), optNumber(args[1]))),
],
[
"set",
1,
function* (thisValue, args) {
const target = self(thisValue, "set")
const offset = optNumber(args[1]) ?? 0
const source = yield* collectBytes(ctx, args[0], "Uint8Array.set")
if (!Number.isInteger(offset) || offset < 0 || source.length + offset > target.bytes.length) {
throw rangeError("Uint8Array.set: the source does not fit at that offset.")
}
target.bytes.set(source, offset)
return undefined
},
],
[
"fill",
1,
(thisValue, args) => {
const target = self(thisValue, "fill")
target.bytes.fill(coerceToNumber(args[0]), optNumber(args[1]), optNumber(args[2]))
return target
},
],
[
"reverse",
0,
(thisValue) => {
const target = self(thisValue, "reverse")
target.bytes.reverse()
return target
},
],
[
"sort",
1,
function* (thisValue, args) {
const target = self(thisValue, "sort")
// Without a comparator, typed arrays sort numerically rather than by string.
if (args[0] === undefined) {
target.bytes.sort()
return target
}
const sorted = yield* sortArray(ctx, [...target.bytes], args[0], "Uint8Array.sort")
target.bytes.set(Uint8Array.from(sorted, coerceToNumber))
return target
},
],
["indexOf", 1, (thisValue, args) => self(thisValue, "indexOf").bytes.indexOf(search(args[0]), optNumber(args[1]))],
[
"lastIndexOf",
1,
(thisValue, args) => {
const target = self(thisValue, "lastIndexOf").bytes
return args.length < 2
? target.lastIndexOf(search(args[0]))
: target.lastIndexOf(search(args[0]), optNumber(args[1]))
},
],
[
"includes",
1,
(thisValue, args) => self(thisValue, "includes").bytes.includes(search(args[0]), optNumber(args[1])),
],
[
"join",
1,
(thisValue, args) => {
const joined = self(thisValue, "join").bytes.join(args[0] === undefined ? "," : coerceToString(args[0]))
checkStringLength(joined.length)
return joined
},
],
["toString", 0, (thisValue) => self(thisValue, "toString").bytes.join(",")],
["toBase64", 0, (thisValue) => self(thisValue, "toBase64").bytes.toBase64()],
["toHex", 0, (thisValue) => self(thisValue, "toHex").bytes.toHex()],
["keys", 0, (thisValue) => hostIterator(builtins, self(thisValue, "keys").bytes.keys())],
["values", 0, (thisValue) => hostIterator(builtins, self(thisValue, "values").bytes.values())],
[
"entries",
0,
(thisValue) =>
hostIterator(
builtins,
self(thisValue, "entries")
.bytes.entries()
.map(([index, byte]) => wrapAll([index, byte])),
),
],
...callbackMethods(
ctx,
"Uint8Array",
self,
(target) => target.bytes,
(values) => wrap(Uint8Array.from(values, coerceToNumber)),
),
])
define(proto, IteratorSymbol, get(proto, "values"), hidden)
return uint8Array
}
export const textEncoderGlobal = <R>(ctx: Interpreter<R>) => {
const builtins = ctx.builtins
const proto = builtins.TextEncoder
const encoder = new TextEncoder()
defineAccessor(proto, "encoding", () => "utf-8")
methods(builtins, proto, [
["encode", 0, (_, args) => new Bytes(builtins.Uint8Array, encoder.encode(coerceToString(args[0] ?? "")))],
])
return constructor(builtins, proto, {
name: "TextEncoder",
call: requiresNew("TextEncoder"),
construct: (_, newTarget) => new Obj(prototypeFrom(newTarget, proto)),
})
}
/** A `TextDecoder` holding the host decoder its label and options configured. */
export class TextDecoderObj extends Obj {
constructor(
proto: Obj,
readonly decoder: TextDecoder,
) {
super(proto)
}
}
// The WHATWG labels for UTF-8, the only encoding CodeMode decodes.
const utf8Labels = new Set(["unicode-1-1-utf-8", "unicode11utf8", "unicode20utf8", "utf-8", "utf8", "x-unicode20utf8"])
export const textDecoderGlobal = <R>(ctx: Interpreter<R>) => {
const builtins = ctx.builtins
const proto = builtins.TextDecoder
const self = (thisValue: Value, name: string) => receiver(TextDecoderObj, thisValue, `TextDecoder.prototype.${name}`)
defineAccessor(proto, "encoding", (thisValue) => self(thisValue, "encoding").decoder.encoding)
defineAccessor(proto, "fatal", (thisValue) => self(thisValue, "fatal").decoder.fatal)
defineAccessor(proto, "ignoreBOM", (thisValue) => self(thisValue, "ignoreBOM").decoder.ignoreBOM)
methods(builtins, proto, [
[
"decode",
0,
(thisValue, args) => {
const decoder = self(thisValue, "decode").decoder
if (args[0] === undefined) return ""
if (!(args[0] instanceof Bytes)) {
throw typeError(`TextDecoder.decode expects a Uint8Array, received ${describeValue(args[0])}.`)
}
try {
return decoder.decode(args[0].bytes)
} catch {
throw typeError(`TextDecoder.decode: the input is not valid ${decoder.encoding}.`)
}
},
],
])
return constructor(builtins, proto, {
name: "TextDecoder",
call: requiresNew("TextDecoder"),
construct: (args, newTarget) => {
const label = args[0] === undefined ? "utf-8" : coerceToString(args[0]).trim().toLowerCase()
if (!utf8Labels.has(label)) throw rangeError(`The "${label}" encoding is not supported; only UTF-8 is.`)
const options = args[1] instanceof Obj ? args[1] : undefined
const flag = (name: string) => options !== undefined && Boolean(get(options, name))
return new TextDecoderObj(
prototypeFrom(newTarget, proto),
new TextDecoder("utf-8", { fatal: flag("fatal"), ignoreBOM: flag("ignoreBOM") }),
)
},
})
}