Repository navigation
Expand file tree
/
Copy pathbytes.ts
More file actions
312 lines (299 loc) · 11.7 KB
/
Copy pathbytes.ts
File metadata and controls
312 lines (299 loc) · 11.7 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
import { Invoke } from "../runtime/signals.js"
import { checkArrayLength, checkStringLength } from "../runtime/limits.js"
import { constructor, methods, prototypeFrom, receiver, requiresNew, iteratorMethods } from "../runtime/native.js"
import { IteratorSymbol, rangeError, syntaxError, typeError } from "../runtime/model.js"
import {
define,
defineAccessor,
get,
hidden,
Bytes,
Obj,
coerceToInteger,
coerceToNumber,
coerceToString,
type Value,
} from "../runtime/objects.js"
import { describeValue } from "../runtime/references.js"
import { requireCallback } from "../runtime/callback.js"
import type { Interpreter } from "../runtime/interpreter.js"
import { sortArray } from "./array.js"
/**
* The bytes a Uint8Array, array, or other iterable of numbers describes, read in the prelude: a new Uint8Array with
* prototype `into`, or set into the Uint8Array `into` at `offset`. The host array clamps each value.
*/
const collectBytes = <R>(
ctx: Interpreter<R>,
source: Value,
name: string,
into: Obj,
offset: number,
mapper?: Value,
thisArg?: Value,
) => {
const callback = mapper === undefined ? undefined : requireCallback(mapper, name)
if (source instanceof Bytes && callback === undefined) return finishBytes(new Uint8Array(source.bytes), into, offset)
return new Invoke(
ctx.prelude.fn("collectBytes"),
undefined,
[source, name, callback, thisArg, into, offset],
undefined,
)
}
export const finishBytes = (bytes: Uint8Array, into: Obj, offset: number): Value => {
if (!(into instanceof Bytes)) return new Bytes(into, bytes)
if (!Number.isInteger(offset) || offset < 0 || bytes.length + offset > into.bytes.length) {
throw rangeError("Uint8Array.set: the source does not fit at that offset.")
}
into.bytes.set(bytes, offset)
return undefined
}
const constructBytes = <R>(ctx: Interpreter<R>, args: Array<Value>, proto: Obj) => {
const source = args[0]
if (source !== null && typeof source === "object") return collectBytes(ctx, source, "new Uint8Array(...)", proto, 0)
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, (_, args) => collectBytes(ctx, args[0], "Uint8Array.from", proto, 0, 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)
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,
(thisValue, args) => {
const target = self(thisValue, "set")
return collectBytes(ctx, args[0], "Uint8Array.set", target, optNumber(args[1]) ?? 0)
},
],
[
"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,
(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
}
return sortArray(ctx, target, args[0], "Uint8Array.sort")
},
],
["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()],
...iteratorMethods(builtins, self),
// The callback methods are the prelude's.
])
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] === undefined ? "" : args[0]))),
],
])
return constructor(builtins, proto, {
name: "TextEncoder",
call: requiresNew("TextEncoder"),
construct: (_, newTarget) => new Obj(prototypeFrom(newTarget, proto)),
})
}
// Replacement mode only needs to identify an incomplete suffix (at most three bytes).
// Fatal mode also needs the queue position after the first error, which the host doesn't expose.
const streamBoundary = (bytes: Uint8Array, fatal: boolean) => {
let next = fatal ? 0 : Math.max(0, bytes.length - 3)
while (next < bytes.length) {
const start = next
const lead = bytes[next++]!
if (lead < 0x80) continue
if (lead < 0xc2 || lead > 0xf4) {
if (fatal) return { end: next, error: true }
continue
}
const width = lead < 0xe0 ? 2 : lead < 0xf0 ? 3 : 4
let lower = lead === 0xe0 ? 0xa0 : lead === 0xf0 ? 0x90 : 0x80
let upper = lead === 0xed ? 0x9f : lead === 0xf4 ? 0x8f : 0xbf
while (next < start + width) {
if (next === bytes.length) return { end: start, error: false }
const byte = bytes[next]!
// A bad continuation is reprocessed as a leading byte, even after a fatal error.
if (byte < lower || byte > upper) {
if (fatal) return { end: next, error: true }
break
}
next++
lower = 0x80
upper = 0xbf
}
}
return { end: next, error: false }
}
const empty = new Uint8Array()
export class TextDecoderObj extends Obj {
queued: Uint8Array = empty
seen = false
constructor(
proto: Obj,
readonly decoder: TextDecoder,
readonly ignoreBOM: boolean,
) {
super(proto)
}
decode(bytes: Uint8Array, stream: boolean) {
if (this.queued.length && bytes.length) {
checkArrayLength(this.queued.length + bytes.length)
const joined = new Uint8Array(this.queued.length + bytes.length)
joined.set(this.queued)
joined.set(bytes, this.queued.length)
bytes = joined
}
if (!bytes.length) bytes = this.queued
const { end, error } = stream ? streamBoundary(bytes, this.decoder.fatal) : { end: bytes.length, error: false }
this.queued = end < bytes.length ? bytes.slice(end) : empty
if (error) throw typeError("TextDecoder.decode: the input is not valid utf-8.")
const stripBOM = !this.ignoreBOM && !this.seen
if (!stream) this.seen = false
try {
// Keep the host decoder stateless: snapshots own the pending bytes and BOM decision.
const text = this.decoder.decode(end === bytes.length ? bytes : bytes.subarray(0, end))
if (stream && text.length) this.seen = true
return stripBOM && text.charCodeAt(0) === 0xfeff ? text.slice(1) : text
} catch {
throw typeError("TextDecoder.decode: the input is not valid utf-8.")
}
}
}
// 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").ignoreBOM)
methods(builtins, proto, [
[
"decode",
0,
(thisValue, args) => {
const decoder = self(thisValue, "decode")
if (args[0] !== undefined && !(args[0] instanceof Bytes)) {
throw typeError(`TextDecoder.decode expects a Uint8Array, received ${describeValue(args[0])}.`)
}
const options = args[1]
if (options !== undefined && typeof options !== "object") {
throw typeError("TextDecoder.decode expects an options object.")
}
const stream = options instanceof Obj && Boolean(get(options, "stream"))
return decoder.decode(args[0]?.bytes ?? empty, stream)
},
],
])
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: true }),
flag("ignoreBOM"),
)
},
})
}