@@ -31,8 +31,13 @@ enum JavaScriptValueKind {
31
31
Function = 6 ,
32
32
}
33
33
34
+ type SwiftRuntimeHeapEntry = {
35
+ id : number ,
36
+ rc : number ,
37
+ }
34
38
class SwiftRuntimeHeap {
35
- private _heapValues : Map < number , any > ;
39
+ private _heapValueById : Map < number , any > ;
40
+ private _heapEntryByValue : Map < any , SwiftRuntimeHeapEntry > ;
36
41
private _heapNextKey : number ;
37
42
38
43
constructor ( ) {
@@ -42,43 +47,48 @@ class SwiftRuntimeHeap {
42
47
} else if ( typeof global !== "undefined" ) {
43
48
_global = global
44
49
}
45
- this . _heapValues = new Map ( ) ;
46
- this . _heapValues . set ( 0 , _global ) ;
50
+ this . _heapValueById = new Map ( ) ;
51
+ this . _heapValueById . set ( 0 , _global ) ;
52
+
53
+ this . _heapEntryByValue = new Map ( ) ;
54
+ this . _heapEntryByValue . set ( _global , { id : 0 , rc : 1 } ) ;
55
+
47
56
// Note: 0 is preserved for global
48
57
this . _heapNextKey = 1 ;
49
58
}
50
59
51
60
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
61
+ const isObject = typeof value == "object" ;
62
+ const entry = this . _heapEntryByValue . get ( value ) ;
63
+ if ( isObject && entry ) {
64
+ entry . rc ++
65
+ return entry . id
56
66
}
57
67
const id = this . _heapNextKey ++ ;
58
- this . _heapValues . set ( id , value )
68
+ this . _heapValueById . set ( id , value )
59
69
if ( isObject ) {
60
- Reflect . set ( value , "swjs_heap_id" , id ) ;
61
- Reflect . set ( value , "swjs_heap_rc" , 1 ) ;
70
+ this . _heapEntryByValue . set ( value , { id : id , rc : 1 } )
62
71
}
63
72
return id
64
73
}
65
74
66
75
freeHeap ( ref : ref ) {
67
- const value = this . _heapValues . get ( ref ) ;
76
+ const value = this . _heapValueById . get ( ref ) ;
68
77
const isObject = typeof value == "object"
69
78
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 )
79
+ const entry = this . _heapEntryByValue . get ( value ) ! ;
80
+ entry . rc -- ;
81
+ if ( entry . rc != 0 ) return ;
82
+
83
+ this . _heapEntryByValue . delete ( value ) ;
84
+ this . _heapValueById . delete ( ref )
75
85
} else {
76
- this . _heapValues . delete ( ref )
86
+ this . _heapValueById . delete ( ref )
77
87
}
78
88
}
79
89
80
90
referenceHeap ( ref : ref ) {
81
- return this . _heapValues . get ( ref )
91
+ return this . _heapValueById . get ( ref )
82
92
}
83
93
}
84
94
0 commit comments