File tree 3 files changed +44
-2
lines changed
IntegrationTests/JavaScriptKitExec/Sources/JavaScriptKitExec
3 files changed +44
-2
lines changed Original file line number Diff line number Diff line change @@ -299,3 +299,27 @@ Object_Conversion: do {
299
299
} catch {
300
300
print ( error)
301
301
}
302
+
303
+ ObjectRef_Lifetime: do {
304
+ // ```js
305
+ // global.globalObject1 = {
306
+ // "prop_1": {
307
+ // "nested_prop": 1,
308
+ // },
309
+ // "prop_2": 2,
310
+ // "prop_3": true,
311
+ // "prop_4": [
312
+ // 3, 4, "str_elm_1", 5,
313
+ // ],
314
+ // ...
315
+ // }
316
+ // ```
317
+
318
+ let identity = JSClosure { $0 [ 0 ] }
319
+ let ref1 = getJSValue ( this: . global, name: " globalObject1 " ) . object!
320
+ let ref2 = identity ( ref1) . object!
321
+ try expectEqual ( ref1. prop_2, . number( 2 ) )
322
+ try expectEqual ( ref2. prop_2, . number( 2 ) )
323
+ } catch {
324
+ print ( error)
325
+ }
Original file line number Diff line number Diff line change 1
1
import _CJavaScriptKit
2
2
3
+ private struct Weak < T: AnyObject > {
4
+ weak var ref : T ?
5
+ }
6
+
7
+ private var cache = [ UInt32 : Weak < JSObjectRef > ] ( )
8
+
3
9
@dynamicMemberLookup
4
10
public class JSObjectRef : Equatable {
5
11
internal var id : UInt32
6
12
init ( id: UInt32 ) {
7
13
self . id = id
8
14
}
9
15
16
+ static func retrieve( id: UInt32 ) -> JSObjectRef {
17
+ if id != 0 , let ref = cache [ id] ? . ref {
18
+ return ref
19
+ } else {
20
+ let ref = JSObjectRef ( id: id)
21
+ cache [ id] = Weak ( ref: ref)
22
+ return ref
23
+ }
24
+ }
25
+
10
26
@_disfavoredOverload
11
27
public subscript( dynamicMember name: String ) -> ( ( JSValueConvertible . . . ) -> JSValue ) ? {
12
28
get {
@@ -46,7 +62,9 @@ public class JSObjectRef: Equatable {
46
62
static let _JS_Predef_Value_Global : UInt32 = 0
47
63
public static let global = JSObjectRef ( id: _JS_Predef_Value_Global)
48
64
49
- deinit { _destroy_ref ( id) }
65
+ deinit {
66
+ _destroy_ref ( id)
67
+ }
50
68
51
69
public static func == ( lhs: JSObjectRef , rhs: JSObjectRef ) -> Bool {
52
70
return lhs. id == rhs. id
Original file line number Diff line number Diff line change @@ -111,7 +111,7 @@ extension RawJSValue: JSValueConvertible {
111
111
let string = String ( decodingCString: UnsafePointer ( buffer) , as: UTF8 . self)
112
112
return . string( string)
113
113
case JavaScriptValueKind_Object:
114
- return . object( JSObjectRef ( id: UInt32 ( payload1) ) )
114
+ return . object( JSObjectRef . retrieve ( id: UInt32 ( payload1) ) )
115
115
case JavaScriptValueKind_Null:
116
116
return . null
117
117
case JavaScriptValueKind_Undefined:
You can’t perform that action at this time.
0 commit comments