From 95f4150c9606aeafc09da049fa4f6e76c3644acb Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Thu, 20 Mar 2025 17:28:30 +1100 Subject: [PATCH] Use a guard to prevent an implicit unwrap --- .../LibSession+SessionMessagingKit.swift | 11 ++--------- SessionMessagingKit/LibSession/Types/Config.swift | 14 ++++++++++++-- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/SessionMessagingKit/LibSession/LibSession+SessionMessagingKit.swift b/SessionMessagingKit/LibSession/LibSession+SessionMessagingKit.swift index 8f82aa7dd..e28083e94 100644 --- a/SessionMessagingKit/LibSession/LibSession+SessionMessagingKit.swift +++ b/SessionMessagingKit/LibSession/LibSession+SessionMessagingKit.swift @@ -608,15 +608,8 @@ public extension LibSession { // Only generate the push data if we need to do a push guard config.needsPush else { return } - guard let data: PendingChanges.PushData = config.push(variant: info.variant) else { - throw LibSessionError( - config, - fallbackError: .unableToGeneratePushData, - logMessage: "Failed to generate push data for \(info.variant) config data, size: \(config.countDescription), error" - ) - } - - result.append(data: data) + // Try to generate the push data (will throw if there is an error) + try result.append(data: config.push(variant: info.variant)) } } diff --git a/SessionMessagingKit/LibSession/Types/Config.swift b/SessionMessagingKit/LibSession/Types/Config.swift index 2786adf11..b9ee340d9 100644 --- a/SessionMessagingKit/LibSession/Types/Config.swift +++ b/SessionMessagingKit/LibSession/Types/Config.swift @@ -124,12 +124,22 @@ public extension LibSession { // MARK: - Functions - func push(variant: ConfigDump.Variant) -> PendingChanges.PushData? { + func push(variant: ConfigDump.Variant) throws -> PendingChanges.PushData? { switch self { case .userProfile(let conf), .contacts(let conf), .convoInfoVolatile(let conf), .userGroups(let conf), .groupInfo(let conf), .groupMembers(let conf): - let cPushData: UnsafeMutablePointer = config_push(conf) + /// The `config_push` function implicitly unwraps it's value but can throw internally so call it in a guard + /// statement to prevent the implicit unwrap from causing a crash (ideally it would return a standard optional + /// so the compiler would warn us but it's not that straight forward when dealing with C) + guard let cPushData: UnsafeMutablePointer = config_push(conf) else { + throw LibSessionError( + self, + fallbackError: .unableToGeneratePushData, + logMessage: "Failed to generate push data for \(variant) config data, size: \(countDescription), error" + ) + } + let pushData: Data = Data( bytes: cPushData.pointee.config, count: cPushData.pointee.config_len