forked from swiftwasm/JavaScriptKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobject-heap.ts
More file actions
59 lines (50 loc) · 1.61 KB
/
object-heap.ts
File metadata and controls
59 lines (50 loc) · 1.61 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
import { globalVariable } from "./find-global.js";
import { ref } from "./types.js";
type SwiftRuntimeHeapEntry = {
id: number;
rc: number;
};
export class JSObjectSpace {
private _heapValueById: Map<number, any>;
private _heapEntryByValue: Map<any, SwiftRuntimeHeapEntry>;
private _heapNextKey: number;
constructor() {
this._heapValueById = new Map();
this._heapValueById.set(1, globalVariable);
this._heapEntryByValue = new Map();
this._heapEntryByValue.set(globalVariable, { id: 1, rc: 1 });
// Note: 0 is preserved for invalid references, 1 is preserved for globalThis
this._heapNextKey = 2;
}
retain(value: any) {
const entry = this._heapEntryByValue.get(value);
if (entry) {
entry.rc++;
return entry.id;
}
const id = this._heapNextKey++;
this._heapValueById.set(id, value);
this._heapEntryByValue.set(value, { id: id, rc: 1 });
return id;
}
retainByRef(ref: ref) {
return this.retain(this.getObject(ref));
}
release(ref: ref) {
const value = this._heapValueById.get(ref);
const entry = this._heapEntryByValue.get(value)!;
entry.rc--;
if (entry.rc != 0) return;
this._heapEntryByValue.delete(value);
this._heapValueById.delete(ref);
}
getObject(ref: ref) {
const value = this._heapValueById.get(ref);
if (value === undefined) {
throw new ReferenceError(
"Attempted to read invalid reference " + ref,
);
}
return value;
}
}