Skip to content

Commit 69af429

Browse files
committed
Add one-time trait activations for pointer-based passing.
1 parent 90b8590 commit 69af429

File tree

9 files changed

+46
-22
lines changed

9 files changed

+46
-22
lines changed

bindings/LDK/Bindings.swift

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,11 @@ open class NativeTraitWrapper: NativeTypeWrapper {
7272
return self
7373
}
7474

75+
public func activateOnce() -> Self {
76+
Bindings.cacheInstance(instance: self)
77+
return self
78+
}
79+
7580
}
7681

7782
public class Bindings {
@@ -6062,7 +6067,7 @@ public class Bindings {
60626067
serWrapper.noOpRetain()
60636068
}
60646069

6065-
return withUnsafePointer(to: arg.cOpaqueStruct!) { (argPointer: UnsafePointer<LDKKeysInterface>) in
6070+
return withUnsafePointer(to: arg.activateOnce().cOpaqueStruct!) { (argPointer: UnsafePointer<LDKKeysInterface>) in
60666071

60676072
Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ(pointer: C2Tuple_BlockHashChannelMonitorZ_read(serWrapper.cOpaqueStruct!, argPointer))
60686073

@@ -6239,7 +6244,7 @@ withUnsafePointer(to: htlc.cOpaqueStruct!) { (htlcPointer: UnsafePointer<LDKHTLC
62396244

62406245
return withUnsafePointer(to: route_params.cOpaqueStruct!) { (route_paramsPointer: UnsafePointer<LDKRouteParameters>) in
62416246
withUnsafePointer(to: network.cOpaqueStruct!) { (networkPointer: UnsafePointer<LDKNetworkGraph>) in
6242-
withUnsafePointer(to: scorer.cOpaqueStruct!) { (scorerPointer: UnsafePointer<LDKScore>) in
6247+
withUnsafePointer(to: scorer.activateOnce().cOpaqueStruct!) { (scorerPointer: UnsafePointer<LDKScore>) in
62436248
withUnsafePointer(to: Bindings.array_to_tuple32(array: random_seed_bytes)) { (random_seed_bytesPointer: UnsafePointer<(UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8)>) in
62446249

62456250
Result_RouteLightningErrorZ(pointer: find_route(Bindings.new_LDKPublicKey(array: our_node_pubkey), route_paramsPointer, networkPointer, first_hopsPointer, logger.activate().cOpaqueStruct!, scorerPointer, random_seed_bytesPointer))
@@ -6332,10 +6337,14 @@ withUnsafePointer(to: Bindings.array_to_tuple32(array: random_seed_bytes)) { (ra
63326337
static var nativelyExposedInstances = [UInt: NativeTraitWrapper]()
63336338
static var nativelyExposedInstanceReferenceCounter = [UInt: Int]()
63346339

6335-
public class func cacheInstance(instance: NativeTraitWrapper) {
6340+
public class func cacheInstance(instance: NativeTraitWrapper, countIdempotently: Bool = false) {
63366341
let key = instance.globalInstanceNumber
63376342
let referenceCount = (Self.nativelyExposedInstanceReferenceCounter[key] ?? 0) + 1
6338-
Self.nativelyExposedInstanceReferenceCounter[key] = referenceCount
6343+
if (!countIdempotently || referenceCount == 1){
6344+
// if we count non-idempotently, always update the counter
6345+
// otherwise, only update the counter the first time
6346+
Self.nativelyExposedInstanceReferenceCounter[key] = referenceCount
6347+
}
63396348
if referenceCount == 1 {
63406349
print("Caching global instance \(key). Cached instance count: \(nativelyExposedInstanceReferenceCounter.count)")
63416350
Self.nativelyExposedInstances[key] = instance
@@ -6352,11 +6361,11 @@ withUnsafePointer(to: Bindings.array_to_tuple32(array: random_seed_bytes)) { (ra
63526361

63536362
public class func pointerToInstance<T: NativeTraitWrapper>(pointer: UnsafeRawPointer, sourceMarker: String?) -> T{
63546363
let key = UInt(bitPattern: pointer)
6355-
let value = Self.nativelyExposedInstances[key] as! T
63566364
let referenceCount = Self.nativelyExposedInstanceReferenceCounter[key] ?? 0
63576365
if referenceCount < 1 {
63586366
print("Bad lookup: non-positive reference count for instance \(key): \(referenceCount)!", severity: .ERROR)
63596367
}
6368+
let value = Self.nativelyExposedInstances[key] as! T
63606369
return value
63616370
}
63626371

@@ -6519,7 +6528,7 @@ withUnsafePointer(to: Bindings.array_to_tuple32(array: random_seed_bytes)) { (ra
65196528
*/
65206529

65216530
public class func get_ldk_swift_bindings_version() -> String {
6522-
return "eb40db30cfc9a35a8947dbbc17d7fdcc05bc3b50"
6531+
return "90b85905ad0889a5368bb8eee79bfbb4d0ff444e"
65236532
}
65246533

65256534
}

bindings/LDK/structs/ChannelMonitor.swift

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -51,9 +51,9 @@ ChannelMonitor_write(objPointer)
5151

5252
return Result_NoneNoneZ(pointer: withUnsafePointer(to: self.cOpaqueStruct!) { (this_argPointer: UnsafePointer<LDKChannelMonitor>) in
5353
withUnsafePointer(to: updates.cOpaqueStruct!) { (updatesPointer: UnsafePointer<LDKChannelMonitorUpdate>) in
54-
withUnsafePointer(to: broadcaster.cOpaqueStruct!) { (broadcasterPointer: UnsafePointer<LDKBroadcasterInterface>) in
55-
withUnsafePointer(to: fee_estimator.cOpaqueStruct!) { (fee_estimatorPointer: UnsafePointer<LDKFeeEstimator>) in
56-
withUnsafePointer(to: logger.cOpaqueStruct!) { (loggerPointer: UnsafePointer<LDKLogger>) in
54+
withUnsafePointer(to: broadcaster.activateOnce().cOpaqueStruct!) { (broadcasterPointer: UnsafePointer<LDKBroadcasterInterface>) in
55+
withUnsafePointer(to: fee_estimator.activateOnce().cOpaqueStruct!) { (fee_estimatorPointer: UnsafePointer<LDKFeeEstimator>) in
56+
withUnsafePointer(to: logger.activateOnce().cOpaqueStruct!) { (loggerPointer: UnsafePointer<LDKLogger>) in
5757
ChannelMonitor_update_monitor(this_argPointer, updatesPointer, broadcasterPointer, fee_estimatorPointer, loggerPointer)
5858
}
5959
}
@@ -91,7 +91,7 @@ ChannelMonitor_get_outputs_to_watch(this_argPointer)
9191
public func load_outputs_to_watch(filter: Filter) -> Void {
9292

9393
return withUnsafePointer(to: self.cOpaqueStruct!) { (this_argPointer: UnsafePointer<LDKChannelMonitor>) in
94-
withUnsafePointer(to: filter.cOpaqueStruct!) { (filterPointer: UnsafePointer<LDKFilter>) in
94+
withUnsafePointer(to: filter.activateOnce().cOpaqueStruct!) { (filterPointer: UnsafePointer<LDKFilter>) in
9595
ChannelMonitor_load_outputs_to_watch(this_argPointer, filterPointer)
9696
}
9797
};
@@ -124,7 +124,7 @@ ChannelMonitor_get_and_clear_pending_events(this_argPointer)
124124
public func get_latest_holder_commitment_txn(logger: Logger) -> [[UInt8]] {
125125

126126
return Bindings.LDKCVec_TransactionZ_to_array(nativeType: withUnsafePointer(to: self.cOpaqueStruct!) { (this_argPointer: UnsafePointer<LDKChannelMonitor>) in
127-
withUnsafePointer(to: logger.cOpaqueStruct!) { (loggerPointer: UnsafePointer<LDKLogger>) in
127+
withUnsafePointer(to: logger.activateOnce().cOpaqueStruct!) { (loggerPointer: UnsafePointer<LDKLogger>) in
128128
ChannelMonitor_get_latest_holder_commitment_txn(this_argPointer, loggerPointer)
129129
}
130130
});

bindings/LDK/structs/PeerManager.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ PeerManager_process_events(this_argPointer)
102102
public func socket_disconnected(descriptor: SocketDescriptor) -> Void {
103103

104104
return withUnsafePointer(to: self.cOpaqueStruct!) { (this_argPointer: UnsafePointer<LDKPeerManager>) in
105-
withUnsafePointer(to: descriptor.cOpaqueStruct!) { (descriptorPointer: UnsafePointer<LDKSocketDescriptor>) in
105+
withUnsafePointer(to: descriptor.activateOnce().cOpaqueStruct!) { (descriptorPointer: UnsafePointer<LDKSocketDescriptor>) in
106106
PeerManager_socket_disconnected(this_argPointer, descriptorPointer)
107107
}
108108
};

bindings/LDK/traits/BindingsType.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ open class BindingsType: NativeTraitWrapper {
7676

7777
public func clone() -> BindingsType {
7878

79-
return withUnsafePointer(to: self.cOpaqueStruct!) { (origPointer: UnsafePointer<LDKType>) in
79+
return withUnsafePointer(to: self.activateOnce().cOpaqueStruct!) { (origPointer: UnsafePointer<LDKType>) in
8080

8181
BindingsType(pointer: Type_clone(origPointer))
8282

bindings/LDK/traits/Router.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ public class NativelyImplementedRouter: Router {
134134

135135
return withUnsafePointer(to: route_params.cOpaqueStruct!) { (route_paramsPointer: UnsafePointer<LDKRouteParameters>) in
136136
withUnsafePointer(to: Bindings.array_to_tuple32(array: payment_hash!)) { (payment_hashPointer: UnsafePointer<(UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8,UInt8)>) in
137-
withUnsafePointer(to: scorer.cOpaqueStruct!) { (scorerPointer: UnsafePointer<LDKScore>) in
137+
withUnsafePointer(to: scorer.activateOnce().cOpaqueStruct!) { (scorerPointer: UnsafePointer<LDKScore>) in
138138

139139
Result_RouteLightningErrorZ(pointer: self.cOpaqueStruct!.find_route(self.cOpaqueStruct!.this_arg, Bindings.new_LDKPublicKey(array: payer), route_paramsPointer, payment_hashPointer, first_hopsPointer, scorerPointer))
140140

bindings/LDK/traits/Sign.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ open class Sign: NativeTraitWrapper {
6363

6464
public func clone() -> Sign {
6565

66-
return withUnsafePointer(to: self.cOpaqueStruct!) { (origPointer: UnsafePointer<LDKSign>) in
66+
return withUnsafePointer(to: self.activateOnce().cOpaqueStruct!) { (origPointer: UnsafePointer<LDKSign>) in
6767

6868
Sign(pointer: Sign_clone(origPointer))
6969

bindings/LDK/traits/SocketDescriptor.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ open class SocketDescriptor: NativeTraitWrapper {
7878

7979
public func clone() -> SocketDescriptor {
8080

81-
return withUnsafePointer(to: self.cOpaqueStruct!) { (origPointer: UnsafePointer<LDKSocketDescriptor>) in
81+
return withUnsafePointer(to: self.activateOnce().cOpaqueStruct!) { (origPointer: UnsafePointer<LDKSocketDescriptor>) in
8282

8383
SocketDescriptor(pointer: SocketDescriptor_clone(origPointer))
8484

@@ -180,7 +180,7 @@ public class NativelyImplementedSocketDescriptor: SocketDescriptor {
180180
public override func eq(other_arg: SocketDescriptor) -> Bool {
181181

182182

183-
return withUnsafePointer(to: other_arg.cOpaqueStruct!) { (other_argPointer: UnsafePointer<LDKSocketDescriptor>) in
183+
return withUnsafePointer(to: other_arg.activateOnce().cOpaqueStruct!) { (other_argPointer: UnsafePointer<LDKSocketDescriptor>) in
184184

185185
self.cOpaqueStruct!.eq(self.cOpaqueStruct!.this_arg, other_argPointer)
186186

src/conversion_helper.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,8 @@ def is_array_type(cls, swift_type: str):
7676

7777
@classmethod
7878
def is_trait_type(cls, raw_rust_type: str):
79+
if raw_rust_type is None:
80+
return False
7981
return raw_rust_type in ConversionHelper.trait_structs
8082

8183
@classmethod
@@ -190,14 +192,18 @@ def prepare_swift_to_native_arguments(cls, argument_types, is_trait_callback=Fal
190192
argument_name = 'initValue'
191193

192194
requires_mutability = not current_argument_details.is_const
195+
is_trait = ConversionHelper.is_trait_type(current_argument_details.rust_obj)
193196

194197
reference_prefix = ''
195198
mutability_infix = ''
199+
trait_activation_infix = ''
196200

197201
non_nullable = current_argument_details.non_nullable
198202

199203
if pass_instance:
200204
argument_name = 'self'
205+
if is_trait:
206+
trait_activation_infix = '.activateOnce()'
201207
if requires_mutability:
202208
# argument_name = '&' + argument_name
203209
reference_prefix = '&'
@@ -249,7 +255,7 @@ def prepare_swift_to_native_arguments(cls, argument_types, is_trait_callback=Fal
249255
''' # print('optional argument:', argument_name, passed_argument_name)
250256
else:
251257
wrapper_return_prefix = '' if pointer_wrapping_depth == 0 else 'return '
252-
pointer_wrapping_prefix += f'{wrapper_return_prefix}withUnsafe{mutability_infix}Pointer(to: {reference_prefix}{argument_name}.cOpaqueStruct!) {{ ({passed_argument_name}: Unsafe{mutability_infix}Pointer<{current_argument_details.rust_obj}>) in\n'
258+
pointer_wrapping_prefix += f'{wrapper_return_prefix}withUnsafe{mutability_infix}Pointer(to: {reference_prefix}{argument_name}{trait_activation_infix}.cOpaqueStruct!) {{ ({passed_argument_name}: Unsafe{mutability_infix}Pointer<{current_argument_details.rust_obj}>) in\n'
253259
pointer_wrapping_suffix += '\n}'
254260
# native_call_prep += current_prep
255261
elif is_cloneable:

templates/BindingsTemplate.swift

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,11 @@ open class NativeTraitWrapper: NativeTypeWrapper {
7272
return self
7373
}
7474

75+
public func activateOnce() -> Self {
76+
Bindings.cacheInstance(instance: self)
77+
return self
78+
}
79+
7580
}
7681

7782
public class Bindings {
@@ -241,10 +246,14 @@ public class Bindings {
241246
static var nativelyExposedInstances = [UInt: NativeTraitWrapper]()
242247
static var nativelyExposedInstanceReferenceCounter = [UInt: Int]()
243248

244-
public class func cacheInstance(instance: NativeTraitWrapper) {
249+
public class func cacheInstance(instance: NativeTraitWrapper, countIdempotently: Bool = false) {
245250
let key = instance.globalInstanceNumber
246251
let referenceCount = (Self.nativelyExposedInstanceReferenceCounter[key] ?? 0) + 1
247-
Self.nativelyExposedInstanceReferenceCounter[key] = referenceCount
252+
if (!countIdempotently || referenceCount == 1){
253+
// if we count non-idempotently, always update the counter
254+
// otherwise, only update the counter the first time
255+
Self.nativelyExposedInstanceReferenceCounter[key] = referenceCount
256+
}
248257
if referenceCount == 1 {
249258
print("Caching global instance \(key). Cached instance count: \(nativelyExposedInstanceReferenceCounter.count)")
250259
Self.nativelyExposedInstances[key] = instance
@@ -261,11 +270,11 @@ public class Bindings {
261270

262271
public class func pointerToInstance<T: NativeTraitWrapper>(pointer: UnsafeRawPointer, sourceMarker: String?) -> T{
263272
let key = UInt(bitPattern: pointer)
264-
let value = Self.nativelyExposedInstances[key] as! T
265273
let referenceCount = Self.nativelyExposedInstanceReferenceCounter[key] ?? 0
266274
if referenceCount < 1 {
267275
print("Bad lookup: non-positive reference count for instance \(key): \(referenceCount)!", severity: .ERROR)
268276
}
277+
let value = Self.nativelyExposedInstances[key] as! T
269278
return value
270279
}
271280

@@ -276,7 +285,7 @@ public class Bindings {
276285
if referenceCount == 0 {
277286
print("Uncaching global instance \(key)")
278287
// TODO: fix counting
279-
// Self.nativelyExposedInstances.removeValue(forKey: key)
288+
Self.nativelyExposedInstances.removeValue(forKey: key)
280289
instance.pointerDebugDescription = nil
281290
} else if referenceCount < 0 {
282291
print("Bad uncache: negative reference count (\(referenceCount)) for instance \(key)!", severity: .ERROR)

0 commit comments

Comments
 (0)