Skip to content

Commit 66064a0

Browse files
Renovate heap system not to pollute object
1 parent 38ae6fd commit 66064a0

File tree

1 file changed

+31
-18
lines changed

1 file changed

+31
-18
lines changed

Diff for: Runtime/src/index.ts

+31-18
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,9 @@ enum JavaScriptValueKind {
3232
}
3333

3434
class SwiftRuntimeHeap {
35-
private _heapValues: Map<number, any>;
35+
private _heapValueById: Map<number, any>;
36+
private _heapIdByValue: Map<any, number>;
37+
private _heapRcByValue: Map<any, number>;
3638
private _heapNextKey: number;
3739

3840
constructor() {
@@ -42,43 +44,54 @@ class SwiftRuntimeHeap {
4244
} else if (typeof global !== "undefined") {
4345
_global = global
4446
}
45-
this._heapValues = new Map();
46-
this._heapValues.set(0, _global);
47+
this._heapValueById = new Map();
48+
this._heapValueById.set(0, _global);
49+
50+
this._heapIdByValue = new Map();
51+
this._heapValueById.set(_global, 0);
52+
53+
this._heapRcByValue = new Map();
54+
4755
// Note: 0 is preserved for global
4856
this._heapNextKey = 1;
4957
}
5058

5159
allocHeap(value: any) {
52-
const isObject = typeof value == "object"
53-
if (isObject && value.swjs_heap_id) {
54-
value.swjs_heap_rc++;
55-
return value.swjs_heap_id
60+
const isObject = typeof value == "object";
61+
const heapId = this._heapIdByValue.get(value);
62+
if (isObject && heapId) {
63+
const rc = this._heapRcByValue.get(value)!;
64+
this._heapRcByValue.set(value, rc + 1);
65+
return heapId
5666
}
5767
const id = this._heapNextKey++;
58-
this._heapValues.set(id, value)
68+
this._heapValueById.set(id, value)
5969
if (isObject) {
60-
Reflect.set(value, "swjs_heap_id", id);
61-
Reflect.set(value, "swjs_heap_rc", 1);
70+
this._heapIdByValue.set(value, id);
71+
this._heapRcByValue.set(value, 1);
6272
}
6373
return id
6474
}
6575

6676
freeHeap(ref: ref) {
67-
const value = this._heapValues.get(ref);
77+
const value = this._heapValueById.get(ref);
6878
const isObject = typeof value == "object"
6979
if (isObject) {
70-
const rc = --value.swjs_heap_rc;
71-
if (rc != 0) return;
72-
delete value.swjs_heap_id;
73-
delete value.swjs_heap_rc;
74-
this._heapValues.delete(ref)
80+
const rc = this._heapRcByValue.get(value)!;
81+
const newRc = rc - 1
82+
this._heapRcByValue.set(value, newRc);
83+
if (newRc != 0) return;
84+
85+
this._heapIdByValue.delete(value);
86+
this._heapRcByValue.delete(value);
87+
this._heapValueById.delete(ref)
7588
} else {
76-
this._heapValues.delete(ref)
89+
this._heapValueById.delete(ref)
7790
}
7891
}
7992

8093
referenceHeap(ref: ref) {
81-
return this._heapValues.get(ref)
94+
return this._heapValueById.get(ref)
8295
}
8396
}
8497

0 commit comments

Comments
 (0)