refactor: replace V8 hidden values with WeakMap / WeakSet (#26659)

This commit is contained in:
Milan Burda 2020-11-24 22:11:39 +01:00 committed by GitHub
parent 0be6c92aa9
commit c8d77cae4a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 29 additions and 19 deletions

View file

@ -1,4 +1,5 @@
const v8Util = process._linkedBinding('electron_common_v8_util');
const callbackIds = new WeakMap<Function, number>();
const locationInfo = new WeakMap<Function, string>();
export class CallbacksRegistry {
private nextId: number = 0
@ -6,7 +7,7 @@ export class CallbacksRegistry {
add (callback: Function) {
// The callback is already added.
let id = v8Util.getHiddenValue<number>(callback, 'callbackId');
let id = callbackIds.get(callback);
if (id != null) return id;
id = this.nextId += 1;
@ -17,7 +18,7 @@ export class CallbacksRegistry {
const stackString = (new Error()).stack;
if (!stackString) return;
let filenameAndLine;
let filenameAndLine: string;
let match;
while ((match = regexp.exec(stackString)) !== null) {
@ -32,8 +33,8 @@ export class CallbacksRegistry {
}
this.callbacks.set(id, callback);
v8Util.setHiddenValue(callback, 'callbackId', id);
v8Util.setHiddenValue(callback, 'location', filenameAndLine);
callbackIds.set(callback, id);
locationInfo.set(callback, filenameAndLine!);
return id;
}
@ -41,6 +42,10 @@ export class CallbacksRegistry {
return this.callbacks.get(id) || function () {};
}
getLocation (callback: Function) {
return locationInfo.get(callback);
}
apply (id: number, ...args: any[]) {
return this.get(id).apply(global, ...args);
}
@ -48,7 +53,7 @@ export class CallbacksRegistry {
remove (id: number) {
const callback = this.callbacks.get(id);
if (callback) {
v8Util.deleteHiddenValue(callback, 'callbackId');
callbackIds.delete(callback);
this.callbacks.delete(id);
}
}