1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-12-28 01:59:06 -05:00
denoland-deno/ext/web/03_abort_signal.js
Aaron O'Mullan f827b93df4
perf(web): optimize AbortController (#12165)
- Use regular class constructor and symbol "private" attributes
- Lazy init Set of follower signals
2021-09-21 17:38:57 +02:00

128 lines
2.9 KiB
JavaScript

// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
"use strict";
// @ts-check
/// <reference path="../../core/internal.d.ts" />
((window) => {
const webidl = window.__bootstrap.webidl;
const { setIsTrusted, defineEventHandler } = window.__bootstrap.event;
const {
Boolean,
Set,
SetPrototypeAdd,
SetPrototypeDelete,
Symbol,
SymbolToStringTag,
TypeError,
} = window.__bootstrap.primordials;
const add = Symbol("add");
const signalAbort = Symbol("signalAbort");
const remove = Symbol("remove");
const aborted = Symbol("aborted");
const abortAlgos = Symbol("abortAlgos");
const illegalConstructorKey = Symbol("illegalConstructorKey");
class AbortSignal extends EventTarget {
static abort() {
const signal = new AbortSignal(illegalConstructorKey);
signal[signalAbort]();
return signal;
}
[add](algorithm) {
if (this[abortAlgos] === null) {
this[abortAlgos] = new Set();
}
SetPrototypeAdd(this[abortAlgos], algorithm);
}
[signalAbort]() {
if (this[aborted]) {
return;
}
this[aborted] = true;
if (this[abortAlgos] !== null) {
for (const algorithm of this[abortAlgos]) {
algorithm();
}
this[abortAlgos] = null;
}
const event = new Event("abort");
setIsTrusted(event, true);
this.dispatchEvent(event);
}
[remove](algorithm) {
this[abortAlgos] && SetPrototypeDelete(this[abortAlgos], algorithm);
}
constructor(key = null) {
if (key != illegalConstructorKey) {
throw new TypeError("Illegal constructor.");
}
super();
this[aborted] = false;
this[abortAlgos] = null;
this[webidl.brand] = webidl.brand;
}
get aborted() {
return Boolean(this[aborted]);
}
get [SymbolToStringTag]() {
return "AbortSignal";
}
}
defineEventHandler(AbortSignal.prototype, "abort");
webidl.configurePrototype(AbortSignal);
class AbortController {
#signal = new AbortSignal(illegalConstructorKey);
get signal() {
return this.#signal;
}
abort() {
this.#signal[signalAbort]();
}
get [SymbolToStringTag]() {
return "AbortController";
}
}
webidl.configurePrototype(AbortController);
webidl.converters["AbortSignal"] = webidl.createInterfaceConverter(
"AbortSignal",
AbortSignal,
);
function newSignal() {
return new AbortSignal(illegalConstructorKey);
}
function follow(followingSignal, parentSignal) {
if (parentSignal.aborted) {
followingSignal[signalAbort]();
} else {
parentSignal[add](() => followingSignal[signalAbort]());
}
}
window.AbortSignal = AbortSignal;
window.AbortController = AbortController;
window.__bootstrap.abortSignal = {
add,
signalAbort,
remove,
follow,
newSignal,
};
})(this);