Rename owsAssert to owsPrecondition

This commit is contained in:
Adam Sharp 2024-07-02 12:19:12 -04:00
parent 893e690d31
commit 34a8cf2bda
No known key found for this signature in database
93 changed files with 184 additions and 181 deletions

View File

@ -463,8 +463,8 @@ final class AppDelegate: UIResponder, UIApplicationDelegate {
) {
Logger.info("")
AssertIsOnMainThread()
owsAssert(!AppReadiness.isAppReady)
owsAssert(!CurrentAppContext().isRunningTests)
owsPrecondition(!AppReadiness.isAppReady)
owsPrecondition(!CurrentAppContext().isRunningTests)
let appContext = launchContext.appContext

View File

@ -10,7 +10,7 @@ public class AppEnvironment: NSObject {
private static var _shared: AppEnvironment?
static func setSharedEnvironment(_ appEnvironment: AppEnvironment) {
owsAssert(self._shared == nil)
owsPrecondition(self._shared == nil)
self._shared = appEnvironment
}

View File

@ -66,7 +66,7 @@ extension SignalApp {
func showLaunchInterface(_ launchInterface: LaunchInterface, launchStartedAt: TimeInterval) {
AssertIsOnMainThread()
owsAssert(AppReadiness.isAppReady)
owsPrecondition(AppReadiness.isAppReady)
let startupDuration = CACurrentMediaTime() - launchStartedAt
let formattedStartupDuration = String(format: "%.3f", startupDuration)

View File

@ -291,7 +291,7 @@ final class CallService: CallServiceStateObserver, CallServiceStateDelegate {
private func updateIsLocalAudioMutedWithMicrophonePermission(call: SignalCall, isLocalAudioMuted: Bool) {
AssertIsOnMainThread()
owsAssert(call === callServiceState.currentCall)
owsPrecondition(call === callServiceState.currentCall)
switch call.mode {
case .groupThread(let call as GroupCall), .callLink(let call as GroupCall):
@ -346,7 +346,7 @@ final class CallService: CallServiceStateObserver, CallServiceStateDelegate {
private func updateIsLocalVideoMutedWithCameraPermissions(call: SignalCall, isLocalVideoMuted: Bool) {
AssertIsOnMainThread()
owsAssert(call === callServiceState.currentCall)
owsPrecondition(call === callServiceState.currentCall)
switch call.mode {
case .groupThread(let call as GroupCall), .callLink(let call as GroupCall):
@ -949,7 +949,7 @@ extension CallService: GroupCallObserver {
case nil, .individual:
owsFail("Can't receive callback without an active group call")
case .groupThread(let currentCall as GroupCall), .callLink(let currentCall as GroupCall):
owsAssert(currentCall === groupCall)
owsPrecondition(currentCall === groupCall)
if currentCall.shouldTerminateOnEndEvent {
callServiceState.terminateCall(call!)
}

View File

@ -131,7 +131,7 @@ class GroupCallRecordRingingCleanupManager {
groupThread: TSGroupThread,
callRecords: [CallRecord]
) async throws {
owsAssert(callRecords.allSatisfy { $0.threadRowId == groupThread.sqliteRowId! })
owsPrecondition(callRecords.allSatisfy { $0.threadRowId == groupThread.sqliteRowId! })
let peekInfo = try await self.groupCallPeekClient.fetchPeekInfo(
groupThread: groupThread

View File

@ -79,7 +79,7 @@ public class IndividualCall: CustomDebugStringConvertible {
func setOutgoingCallIdAndUpdateCallRecord(_ callId: UInt64) {
AssertIsOnMainThread()
owsAssert(self.direction == .outgoing)
owsPrecondition(self.direction == .outgoing)
Logger.info("")
self.callId = callId

View File

@ -1124,7 +1124,7 @@ final class IndividualCallService: CallServiceStateObserver {
*/
private func handleConnected(call: SignalCall) {
AssertIsOnMainThread()
owsAssert(call === callServiceState.currentCall)
owsPrecondition(call === callServiceState.currentCall)
Logger.info("call: \(call)")
// End the background task.

View File

@ -58,7 +58,7 @@ extension CallsListViewController {
maxCachedViewModelCount: Int = 150,
maxCoalescedCallsInOneViewModel: UInt = 50
) {
owsAssert(
owsPrecondition(
maxCachedViewModelCount >= viewModelPageSize,
"Must be able to cache at least one page of view models!"
)
@ -265,7 +265,7 @@ extension CallsListViewController {
tx: tx
)
owsAssert(rehydratedCount <= viewModelsToLoadCount)
owsPrecondition(rehydratedCount <= viewModelsToLoadCount)
viewModelsToLoadCount -= rehydratedCount
if viewModelsToLoadCount == 0 {
@ -325,7 +325,7 @@ extension CallsListViewController {
return true
case .loaded(let newViewModels):
owsAssert(newViewModels.count > 0)
owsPrecondition(newViewModels.count > 0)
loadedViewModelReferences.prepend(
newElements: newViewModels.map { $0.reference }
@ -456,7 +456,7 @@ extension CallsListViewController {
maxCount: UInt,
tx: DBReadTransaction
) -> [CallViewModel] {
owsAssert(
owsPrecondition(
cachedViewModels.isEmpty || cachedViewModels.last!.reference == loadedViewModelReferences.last!,
"Unexpectedly loading brand new view models, but last loaded view model reference does not have a cached view model!"
)
@ -513,7 +513,7 @@ extension CallsListViewController {
}
}
owsAssert(
owsPrecondition(
groupedCallRecordsForViewModels.allSatisfy { !$0.isEmpty },
"Had an empty grouping for a view model. How did this happen?"
)
@ -583,7 +583,7 @@ extension CallsListViewController {
currentNewestViewModel: CallViewModel,
tx: DBReadTransaction
) -> LoadBrandNewViewModelsNewerResult {
owsAssert(currentNewestViewModel.reference == loadedViewModelReferences.first)
owsPrecondition(currentNewestViewModel.reference == loadedViewModelReferences.first)
let newCallRecordsCursor: CallRecordCursor = callRecordLoader.loadCallRecords(
loadDirection: .newerThan(
@ -604,7 +604,7 @@ extension CallsListViewController {
///
/// We'll reverse them here, and return them ordered descending, to
/// make things easier on our callers.
owsAssert(pageOfNewCallRecordsAsc.isSortedByTimestamp(.ascending))
owsPrecondition(pageOfNewCallRecordsAsc.isSortedByTimestamp(.ascending))
let pageOfNewCallRecords = pageOfNewCallRecordsAsc.reversed()
if pageOfNewCallRecords.isEmpty {

View File

@ -815,19 +815,19 @@ class CallsListViewController: OWSViewController, HomeTabViewController, CallSer
deps: Dependencies,
tx: SDSAnyReadTransaction
) -> CallViewModel {
owsAssert(
owsPrecondition(
coalescedCallRecords.allSatisfy { $0.threadRowId == primaryCallRecord.threadRowId },
"Coalesced call records were for a different thread than the primary!"
)
owsAssert(
owsPrecondition(
coalescedCallRecords.allSatisfy { $0.callDirection == primaryCallRecord.callDirection },
"Coalesced call records were of a different direction than the primary!"
)
owsAssert(
owsPrecondition(
coalescedCallRecords.allSatisfy { $0.callStatus.isMissedCall == primaryCallRecord.callStatus.isMissedCall },
"Coalesced call records were of a different missed status than the primary!"
)
owsAssert(
owsPrecondition(
([primaryCallRecord] + coalescedCallRecords).isSortedByTimestamp(.descending),
"Primary and coalesced call records were not ordered descending by timestamp!"
)
@ -1308,7 +1308,7 @@ extension CallsListViewController: UITableViewDelegate {
private func viewModel(
forIndexPathThatShouldHaveOne indexPath: IndexPath
) -> CallViewModel? {
owsAssert(
owsPrecondition(
indexPath.section == Section.existingCalls.rawValue,
"Unexpected section for index path: \(indexPath.section)"
)

View File

@ -1354,7 +1354,7 @@ extension GroupCallViewController: CallViewControllerWindowReference {
extension GroupCallViewController: GroupCallObserver {
func groupCallLocalDeviceStateChanged(_ call: GroupCall) {
AssertIsOnMainThread()
owsAssert(self.groupCall === call)
owsPrecondition(self.groupCall === call)
guard self.isReadyToHandleObserver else {
return
}
@ -1373,7 +1373,7 @@ extension GroupCallViewController: GroupCallObserver {
func groupCallRemoteDeviceStatesChanged(_ call: GroupCall) {
AssertIsOnMainThread()
owsAssert(self.groupCall === call)
owsPrecondition(self.groupCall === call)
guard self.isReadyToHandleObserver else {
return
}
@ -1388,7 +1388,7 @@ extension GroupCallViewController: GroupCallObserver {
func groupCallPeekChanged(_ call: GroupCall) {
AssertIsOnMainThread()
owsAssert(self.groupCall === call)
owsPrecondition(self.groupCall === call)
guard self.isReadyToHandleObserver else {
return
}
@ -1398,7 +1398,7 @@ extension GroupCallViewController: GroupCallObserver {
func groupCallEnded(_ call: GroupCall, reason: GroupCallEndReason) {
AssertIsOnMainThread()
owsAssert(self.groupCall === call)
owsPrecondition(self.groupCall === call)
guard self.isReadyToHandleObserver else {
return
}
@ -1470,7 +1470,7 @@ extension GroupCallViewController: GroupCallObserver {
func groupCallReceivedReactions(_ call: GroupCall, reactions: [SignalRingRTC.Reaction]) {
AssertIsOnMainThread()
owsAssert(self.groupCall === call)
owsPrecondition(self.groupCall === call)
guard self.isReadyToHandleObserver else {
return
}
@ -1508,7 +1508,7 @@ extension GroupCallViewController: GroupCallObserver {
func groupCallReceivedRaisedHands(_ call: GroupCall, raisedHands: [DemuxId]) {
AssertIsOnMainThread()
owsAssert(self.groupCall === call)
owsPrecondition(self.groupCall === call)
guard self.isReadyToHandleObserver else {
return
}
@ -1518,7 +1518,7 @@ extension GroupCallViewController: GroupCallObserver {
func handleUntrustedIdentityError(_ call: GroupCall) {
AssertIsOnMainThread()
owsAssert(self.groupCall === call)
owsPrecondition(self.groupCall === call)
guard self.isReadyToHandleObserver else {
return
}

View File

@ -81,7 +81,7 @@ class SimulatorCallUIAdaptee: NSObject, CallUIAdaptee {
func localHangupCall(_ call: SignalCall) {
AssertIsOnMainThread()
// If both parties hang up at the same moment, call might already be nil.
owsAssert(self.callService.callServiceState.currentCall == nil || call.localId == self.callService.callServiceState.currentCall?.localId)
owsPrecondition(self.callService.callServiceState.currentCall == nil || call.localId == self.callService.callServiceState.currentCall?.localId)
callService.handleLocalHangupCall(call)
}
@ -105,13 +105,13 @@ class SimulatorCallUIAdaptee: NSObject, CallUIAdaptee {
func setIsMuted(call: SignalCall, isMuted: Bool) {
AssertIsOnMainThread()
owsAssert(call.localId == self.callService.callServiceState.currentCall?.localId)
owsPrecondition(call.localId == self.callService.callServiceState.currentCall?.localId)
self.callService.updateIsLocalAudioMuted(isLocalAudioMuted: isMuted)
}
func setHasLocalVideo(call: SignalCall, hasLocalVideo: Bool) {
AssertIsOnMainThread()
owsAssert(call.localId == self.callService.callServiceState.currentCall?.localId)
owsPrecondition(call.localId == self.callService.callServiceState.currentCall?.localId)
self.callService.updateIsLocalVideoMuted(isLocalVideoMuted: !hasLocalVideo)
}
}

View File

@ -25,7 +25,7 @@ class UsernameLinkQRCodeColorPickerViewController: OWSTableViewController2 {
qrCodeTemplateImage: UIImage,
delegate: UsernameLinkQRCodeColorPickerDelegate
) {
owsAssert(qrCodeTemplateImage.renderingMode == .alwaysTemplate)
owsPrecondition(qrCodeTemplateImage.renderingMode == .alwaysTemplate)
self.startingColor = currentColor
self.currentColor = currentColor

View File

@ -119,7 +119,7 @@ extension Bitmaps.Image {
dimensionPercentage percentage: CGFloat,
paddingPoints: Int
) -> Bitmaps.Rect {
owsAssert(
owsPrecondition(
percentage < 0.5, // Roughly the dimension percentage for deadzoning 30% of the surface area
"Deadzoning too much of a QR code means it might not scan!"
)

View File

@ -161,7 +161,7 @@ class DatabaseRecoveryViewController<SetupResult>: OWSViewController {
@objc
private func didTapToExportDatabase() {
owsAssert(DebugFlags.internalSettings, "Only internal users can export databases")
owsPrecondition(DebugFlags.internalSettings, "Only internal users can export databases")
SignalApp.showExportDatabaseUI(from: self)
}

View File

@ -292,7 +292,7 @@ class DonateChoosePaymentMethodSheet: OWSTableSheetViewController {
.filter(supportedPaymentMethods.contains)
.map(createButtonFor(paymentMethod:))
owsAssert(!paymentMethodButtons.isEmpty, "Expected at least one payment method")
owsPrecondition(!paymentMethodButtons.isEmpty, "Expected at least one payment method")
let stackView = UIStackView(arrangedSubviews: paymentMethodButtons)
stackView.axis = .vertical

View File

@ -37,7 +37,7 @@ extension DonateViewController {
for: .applePay(payment: payment)
)
}.done(on: DispatchQueue.main) { confirmedIntent -> Void in
owsAssert(
owsPrecondition(
confirmedIntent.redirectToUrl == nil,
"[Donations] There shouldn't be a 3DS redirect for Apple Pay"
)

View File

@ -310,7 +310,7 @@ extension DonateViewController {
}
fileprivate func selectSubscriptionLevel(_ newValue: SubscriptionLevel) -> MonthlyState {
owsAssert(subscriptionLevels.contains(newValue), "Subscription level not found")
owsPrecondition(subscriptionLevels.contains(newValue), "Subscription level not found")
return MonthlyState(
subscriptionLevels: subscriptionLevels,
selectedCurrencyCode: selectedCurrencyCode,

View File

@ -9,7 +9,7 @@ import SignalServiceKit
extension DonationPaymentDetailsViewController {
func show3DS(for redirectUrl: URL) -> Promise<String> {
owsAssert(
owsPrecondition(
threeDSecureAuthenticationSession == nil,
"[Donations] Unexpectedly already had a 3DS authentication session going"
)
@ -53,7 +53,7 @@ extension DonationPaymentDetailsViewController {
session.presentationContextProvider = self
owsAssert(
owsPrecondition(
session.start(),
"[Donations] Failed to start 3DS authentication session. Was it set up correctly?"
)

View File

@ -68,7 +68,7 @@ extension DonationPaymentDetailsViewController {
Logger.info("[Gifting] Gifting card donation finished")
self?.onFinished(nil)
}.catch(on: DispatchQueue.main) { [weak self] error in
owsAssert(error is DonationViewsUtil.Gifts.SendGiftError)
owsPrecondition(error is DonationViewsUtil.Gifts.SendGiftError)
Logger.warn("[Gifting] Gifting card donation failed")
self?.onFinished(error)

View File

@ -619,7 +619,7 @@ public class ChatListViewController: OWSViewController, HomeTabViewController {
@objc
private func pullToRefreshPerformed(_ refreshControl: UIRefreshControl) {
AssertIsOnMainThread()
owsAssert(DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isPrimaryDevice == false)
owsPrecondition(DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isPrimaryDevice == false)
syncManager.sendAllSyncRequestMessages(timeout: 20).ensure {
refreshControl.endRefreshing()

View File

@ -108,7 +108,7 @@ class MediaGalleryCellItemPhotoVideo: PhotoGridItem {
}
private var videoDurationPromise: Promise<TimeInterval> {
owsAssert(galleryItem.isVideo)
owsPrecondition(galleryItem.isVideo)
switch galleryItem.attachmentStream.attachmentStream.concreteStreamType {
case .legacy(let tSAttachment):
return TSAttachmentVideoDurationHelper.shared.promisedDuration(

View File

@ -18,7 +18,7 @@ extension IndexSet {
///
/// For example, if `self` contains { 5, 6, 7 } then `nthIndex(1)` returns `6`.
func nthIndex(_ n: Int) -> Element? {
owsAssert(n >= 0)
owsPrecondition(n >= 0)
guard n < count else {
return nil
}
@ -98,7 +98,7 @@ struct MediaGalleryCollectionViewUpdater {
let originalNumberOfItems: Int
mutating func remove(at i: Int) {
owsAssert(i < survivors.count)
owsPrecondition(i < survivors.count)
if let index = survivors.nthIndex(i) {
// Delete an original item.
survivors.remove(index)

View File

@ -234,7 +234,7 @@ internal struct MediaGallerySections<Loader: MediaGallerySectionLoader, UpdateUs
}
internal mutating func loadInitialSection(for date: GalleryDate, transaction: SDSAnyReadTransaction) {
owsAssert(itemsBySection.isEmpty, "already has sections, use loadEarlierSections or loadLaterSections")
owsPrecondition(itemsBySection.isEmpty, "already has sections, use loadEarlierSections or loadLaterSections")
let rowids = loader.rowIdsAndDatesOfItemsInSection(
for: date,
offset: 0,
@ -474,7 +474,7 @@ internal struct MediaGallerySections<Loader: MediaGallerySectionLoader, UpdateUs
///
/// This is essentially a more powerful version of `indexPath(after:)`.
internal func resolveNaiveEndIndex(_ naiveIndex: Int, relativeToSection initialSectionIndex: Int) -> MediaGalleryIndexPath? {
owsAssert(naiveIndex >= 0, "should not be used for indexes before the current section")
owsPrecondition(naiveIndex >= 0, "should not be used for indexes before the current section")
var currentSectionIndex = initialSectionIndex
var limitInCurrentSection = naiveIndex
@ -632,7 +632,7 @@ internal struct MediaGallerySections<Loader: MediaGallerySectionLoader, UpdateUs
guard let naiveRange = resolveLoadItemsRequest(request) else {
return IndexSet()
}
owsAssert(!naiveRange.range.isEmpty)
owsPrecondition(!naiveRange.range.isEmpty)
var numNewlyLoadedEarlierSections: Int = 0
var numNewlyLoadedLaterSections: Int = 0
@ -694,7 +694,7 @@ internal struct MediaGallerySections<Loader: MediaGallerySectionLoader, UpdateUs
var slot = slots[itemIndex]
if let loadedItem = slot.item {
owsAssert(loadedItem.attachmentId == resourceId)
owsPrecondition(loadedItem.attachmentId == resourceId)
return
}
@ -1164,7 +1164,7 @@ internal struct MediaGallerySections<Loader: MediaGallerySectionLoader, UpdateUs
///
/// `path` must be a valid path for the items currently loaded.
internal func loadedItem(at path: MediaGalleryIndexPath) -> Item? {
owsAssert(path.count == 2)
owsPrecondition(path.count == 2)
guard let slot = state.itemsBySection[safe: path.section]?.value[safe: path.item] else {
owsFailDebug("invalid path \(path)")
return nil
@ -1193,7 +1193,7 @@ internal struct MediaGallerySections<Loader: MediaGallerySectionLoader, UpdateUs
///
/// If `path` refers to the last item in the loaded sections, returns `nil`.
internal func indexPath(after path: MediaGalleryIndexPath) -> MediaGalleryIndexPath? {
owsAssert(path.count == 2)
owsPrecondition(path.count == 2)
var result = path
// Next item?
@ -1218,7 +1218,7 @@ internal struct MediaGallerySections<Loader: MediaGallerySectionLoader, UpdateUs
///
/// If `path` refers to the first item in the loaded sections, returns `nil`.
internal func indexPath(before path: MediaGalleryIndexPath) -> MediaGalleryIndexPath? {
owsAssert(path.count == 2)
owsPrecondition(path.count == 2)
var result = path
// Previous item?

View File

@ -40,7 +40,7 @@ extension MediaTileViewController: MediaGalleryCollectionViewUpdaterDelegate {
func updaterDidFinish(numberOfSectionsBefore: Int, numberOfSectionsAfter: Int) {
Logger.debug("\(numberOfSectionsBefore) -> \(numberOfSectionsAfter)")
owsAssert(numberOfSectionsAfter == mediaGallery.galleryDates.count)
owsPrecondition(numberOfSectionsAfter == mediaGallery.galleryDates.count)
if numberOfSectionsBefore == 0 && numberOfSectionsAfter > 0 {
// Adding a "load newer" section. It goes at the end.
collectionView?.insertSections(IndexSet(integer: localSection(numberOfSectionsAfter)))

View File

@ -93,7 +93,7 @@ extension AddToBlockListViewController: RecipientPickerDelegate, UsernameLinkSca
case .address(let address):
#if DEBUG
let isBlocked = blockingManager.isAddressBlocked(address, transaction: transaction)
owsAssert(!isBlocked, "It should be impossible to see a blocked connection in this view")
owsPrecondition(!isBlocked, "It should be impossible to see a blocked connection in this view")
#endif
return nil
case .group(let thread):

View File

@ -139,7 +139,7 @@ public class AddToGroupViewController: OWSTableViewController2 {
private func addToGroup(_ groupThread: TSGroupThread, shortName: String) {
AssertIsOnMainThread()
owsAssert(groupThread.isGroupV2Thread) // non-gv2 filtered above when fetching groups
owsPrecondition(groupThread.isGroupV2Thread) // non-gv2 filtered above when fetching groups
guard let serviceId = self.address.serviceId else {
GroupViewUtils.showInvalidGroupMemberAlert(fromViewController: self)

View File

@ -164,7 +164,7 @@ class NSEEnvironment: Dependencies {
private func setAppIsReady() {
AssertIsOnMainThread()
owsAssert(!AppReadiness.isAppReady)
owsPrecondition(!AppReadiness.isAppReady)
// Note that this does much more than set a flag; it will also run all deferred blocks.
AppReadiness.setAppIsReady()

View File

@ -62,7 +62,7 @@ public enum PniDistribution {
registrationId: UInt32,
deviceMessage: DeviceMessage
) {
owsAssert(deviceId == deviceMessage.destinationDeviceId)
owsPrecondition(deviceId == deviceMessage.destinationDeviceId)
devicePniSignedPreKeys["\(deviceId)"] = signedPreKey
devicePniPqLastResortPreKeys["\(deviceId)"] = pqLastResortPreKey

View File

@ -485,7 +485,7 @@ private extension IncomingCallEventSyncMessageManagerImpl {
syncMessageTimestamp: UInt64,
tx: DBWriteTransaction
) {
owsAssert(callInteraction.uniqueThreadId == thread.uniqueId)
owsPrecondition(callInteraction.uniqueThreadId == thread.uniqueId)
markAsReadShims.markThingsAsReadForIncomingSyncMessage(
callInteraction: callInteraction,

View File

@ -54,7 +54,7 @@ final class DeletedCallRecordCleanupManagerImpl: DeletedCallRecordCleanupManager
func release() {
let isUnlocked = lock.tryToClearFlag()
owsAssert(isUnlocked)
owsPrecondition(isUnlocked)
}
}
@ -151,7 +151,7 @@ final class DeletedCallRecordCleanupManagerImpl: DeletedCallRecordCleanupManager
private func scheduleCleanup(
beginningWith recordToScheduleExpiration: DeletedCallRecord
) {
owsAssert(cleanupLock.get())
owsPrecondition(cleanupLock.get())
let secondsUntilNextCleanupPass: TimeInterval = max(
recordToScheduleExpiration.secondsUntilExpiration(

View File

@ -202,7 +202,7 @@ class DeletedCallRecordStoreImpl: DeletedCallRecordStore {
equalityClauses.append("\(column.rawValue) = ?")
equalityArgs.append(value)
case .ascending(let column):
owsAssert(
owsPrecondition(
orderingClause == nil,
"Multiple ordering clauses! How did that happen?"
)

View File

@ -33,7 +33,7 @@ public struct E164: Equatable, Hashable, Codable, CustomDebugStringConvertible {
}
public var uint64Value: UInt64 {
owsAssert(stringValue.first == "+")
owsPrecondition(stringValue.first == "+")
return UInt64(stringValue.dropFirst())!
}

View File

@ -216,7 +216,7 @@ class RecipientMergerImpl: RecipientMerger {
) -> SignalRecipient {
// The caller checks this, but we assert here to maintain consistency with
// all the other merging methods that check this themselves.
owsAssert(!localIdentifiers.containsAnyOf(aci: serviceIds.aci, phoneNumber: phoneNumber, pni: serviceIds.pni))
owsPrecondition(!localIdentifiers.containsAnyOf(aci: serviceIds.aci, phoneNumber: phoneNumber, pni: serviceIds.pni))
let updatedValues = { () -> (phoneNumber: E164, pni: Pni)? in
let pni = serviceIds.pni

View File

@ -160,23 +160,23 @@ lastVisibleSortIdOnScreenPercentageObsolete:lastVisibleSortIdOnScreenPercentageO
BOOL didAvatarChange = ![NSObject isNullableObject:newGroupModel.avatarHash equalTo:self.groupModel.avatarHash];
BOOL didNameChange = ![newGroupModel.groupNameOrDefault isEqualToString:self.groupModel.groupNameOrDefault];
[self anyUpdateGroupThreadWithTransaction:transaction
block:^(TSGroupThread *thread) {
if ([thread.groupModel isKindOfClass:TSGroupModelV2.class]) {
if (![newGroupModel isKindOfClass:TSGroupModelV2.class]) {
// Can't downgrade a v2 group to a v1 group.
OWSFail(@"Invalid group model.");
} else {
// Can't downgrade a v2 group to an earlier revision.
TSGroupModelV2 *oldGroupModelV2
= (TSGroupModelV2 *)thread.groupModel;
TSGroupModelV2 *newGroupModelV2 = (TSGroupModelV2 *)newGroupModel;
OWSAssert(oldGroupModelV2.revision <= newGroupModelV2.revision);
}
}
[self
anyUpdateGroupThreadWithTransaction:transaction
block:^(TSGroupThread *thread) {
if ([thread.groupModel isKindOfClass:TSGroupModelV2.class]) {
if (![newGroupModel isKindOfClass:TSGroupModelV2.class]) {
// Can't downgrade a v2 group to a v1 group.
OWSFail(@"Invalid group model.");
} else {
// Can't downgrade a v2 group to an earlier revision.
TSGroupModelV2 *oldGroupModelV2 = (TSGroupModelV2 *)thread.groupModel;
TSGroupModelV2 *newGroupModelV2 = (TSGroupModelV2 *)newGroupModel;
OWSPrecondition(oldGroupModelV2.revision <= newGroupModelV2.revision);
}
}
thread.groupModel = [newGroupModel copy];
}];
thread.groupModel = [newGroupModel copy];
}];
[self updateGroupMemberRecordsWithTransaction:transaction];
// We only need to re-index the group if the group name changed.

View File

@ -33,14 +33,14 @@ class ScrubbingLogFormatter: NSObject, DDLogFormatter {
// It's important to have some padding because we use that to mark the end
// of the groupId. If we don't have padding, then we need to sort the
// groupId Replacements from longest to shortest.
owsAssert(base64Padding != 0)
owsPrecondition(base64Padding != 0)
let unredactedLength = 3
let redactedLength = base64Length - base64Padding - unredactedLength
// This assertion exists to prevent someone from updating the values and forgetting to
// update things here.
owsAssert(prefix == "g" && redactedLength >= 1)
owsPrecondition(prefix == "g" && redactedLength >= 1)
let base64Character = "A-Za-z0-9+/"
let paddingCharacter = "="

View File

@ -124,8 +124,8 @@ public class AppSetup {
// is locked, the download will fail if the temporary directory is
// NSFileProtectionComplete.
let temporaryDirectory = NSTemporaryDirectory()
owsAssert(OWSFileSystem.ensureDirectoryExists(temporaryDirectory))
owsAssert(OWSFileSystem.protectFileOrFolder(atPath: temporaryDirectory, fileProtectionType: .completeUntilFirstUserAuthentication))
owsPrecondition(OWSFileSystem.ensureDirectoryExists(temporaryDirectory))
owsPrecondition(OWSFileSystem.protectFileOrFolder(atPath: temporaryDirectory, fileProtectionType: .completeUntilFirstUserAuthentication))
let tsConstants = TSConstants.shared
let keyValueStoreFactory = testDependencies.keyValueStoreFactory ?? SDSKeyValueStoreFactory()

View File

@ -196,7 +196,7 @@ class GroupUpdateInfoMessageInserterImpl: GroupUpdateInfoMessageInserter {
/// compute above will never be empty. Even if we get a strange group
/// update that somehow doesn't produce a diff, we'll get back a list
/// with a single "generic group update" item in it.
owsAssert(!updateItemsForNewMessage.isEmpty)
owsPrecondition(!updateItemsForNewMessage.isEmpty)
let infoMessage = TSInfoMessage.newGroupUpdateInfoMessage(
timestamp: dateProvider().ows_millisecondsSince1970,
spamReportingMetadata: spamReportingMetadata,

View File

@ -392,7 +392,7 @@ public struct GroupV2Change {
public init(snapshot: GroupV2Snapshot?,
changeActionsProto: GroupsProtoGroupChangeActions?,
downloadedAvatars: GroupV2DownloadedAvatars) {
owsAssert(snapshot != nil || changeActionsProto != nil)
owsPrecondition(snapshot != nil || changeActionsProto != nil)
self.snapshot = snapshot
self.changeActionsProto = changeActionsProto
self.downloadedAvatars = downloadedAvatars
@ -578,7 +578,7 @@ public class MockGroupsV2: GroupsV2 {
public func groupId(forGroupSecretParamsData groupSecretParamsData: Data) throws -> Data {
if CurrentAppContext().isRunningTests {
owsAssert(groupSecretParamsData.count >= 32)
owsPrecondition(groupSecretParamsData.count >= 32)
return groupSecretParamsData.subdata(in: Int(0)..<Int(32))
}
owsFail("Not implemented.")
@ -586,8 +586,8 @@ public class MockGroupsV2: GroupsV2 {
public func v2GroupId(forV1GroupId v1GroupId: Data) -> Data? {
let v2GroupId = v1GroupId + v1GroupId
owsAssert(GroupManager.isV1GroupId(v1GroupId))
owsAssert(GroupManager.isV2GroupId(v2GroupId))
owsPrecondition(GroupManager.isV1GroupId(v1GroupId))
owsPrecondition(GroupManager.isV2GroupId(v2GroupId))
return v2GroupId
}

View File

@ -150,7 +150,7 @@ public final class MessageSenderJobRecord: JobRecord, FactoryInitializableFromRe
transientMessage: TSOutgoingMessage,
isHighPriority: Bool
) {
owsAssert(
owsPrecondition(
transientMessage.shouldBeSaved.negated
&& !(transientMessage is OutgoingStoryMessage)
&& !(transientMessage is OWSSyncContactsMessage),

View File

@ -13,7 +13,7 @@ NS_ASSUME_NONNULL_BEGIN
static void logUnconditionally(
DDLogFlag flag, const char *file, BOOL shouldTrimFilePath, NSUInteger line, const char *function, NSString *message)
{
OWSCAssert(ShouldLogFlag(flag));
OWSCPrecondition(ShouldLogFlag(flag));
NSString *fileObj = [NSString stringWithFormat:@"%s", file];
fileObj = shouldTrimFilePath ? fileObj.lastPathComponent : fileObj;
DDLogMessage *logMessage = [[DDLogMessage alloc] initWithMessage:message

View File

@ -60,7 +60,7 @@ final class DeleteForMeAddressableMessageFinderImpl: DeleteForMeAddressableMessa
threadUniqueId: threadUniqueId,
sdsTx: SDSDB.shimOnlyBridge(tx)
).iterate { interaction in
owsAssert(
owsPrecondition(
interaction is TSIncomingMessage || interaction is TSOutgoingMessage,
"Unexpected interaction type! \(type(of: interaction))"
)

View File

@ -61,10 +61,10 @@ extension DeleteForMeSyncMessage {
func registerMessageDeletedFromThread(_ message: TSMessage) {
do {
let messageRowId = message.sqliteRowId!
owsAssert(messageRowId < lastAddedMessageRowId)
owsPrecondition(messageRowId < lastAddedMessageRowId)
lastAddedMessageRowId = messageRowId
owsAssert(message.uniqueThreadId == threadUniqueId)
owsPrecondition(message.uniqueThreadId == threadUniqueId)
}
guard let addressableMessage: AddressableMessage = .addressing(

View File

@ -213,7 +213,7 @@ final class InteractionDeleteManagerImpl: InteractionDeleteManager {
) {
switch sideEffects.deleteForMeSyncMessage {
case .sendSyncMessage(let interactionsThread):
owsAssert(
owsPrecondition(
interactions.allSatisfy { $0.uniqueThreadId == interactionsThread.uniqueId },
"Thread did not match interaction!"
)

View File

@ -33,7 +33,7 @@ public extension TSInfoMessage {
groupThread: TSGroupThread,
updateItems: [PersistableGroupUpdateItem]
) -> TSInfoMessage {
owsAssert(!updateItems.isEmpty)
owsPrecondition(!updateItems.isEmpty)
var userInfoForNewMessage: [InfoMessageUserInfoKey: Any] = [:]

View File

@ -215,7 +215,7 @@ public class MessageFetcherJob: NSObject {
}
private var isReadyToFetchMessagesViaRest: Bool {
owsAssert(CurrentAppContext().isNSE)
owsPrecondition(CurrentAppContext().isNSE)
// The NSE has tight memory constraints.
// For perf reasons, MessageProcessor keeps its queue in memory.

View File

@ -619,7 +619,7 @@ private struct ProcessingRequestBuilder {
for decryptedEnvelope: DecryptedIncomingEnvelope,
tx: SDSAnyWriteTransaction
) -> ProcessingRequest.State {
owsAssert(CurrentAppContext().shouldProcessIncomingMessages)
owsPrecondition(CurrentAppContext().shouldProcessIncomingMessages)
// Pre-processing has to happen during the same transaction that performed
// decryption.

View File

@ -1212,7 +1212,7 @@ public class MessageSender: Dependencies {
) async throws -> [SentDeviceMessage] {
// The caller has access to the error, so they must throw it if no more
// retries are allowed.
owsAssert(remainingAttempts > 0)
owsPrecondition(remainingAttempts > 0)
let message = messageSend.message
let serviceId = messageSend.serviceId

View File

@ -306,7 +306,7 @@ public class OWSIdentityManagerImpl: OWSIdentityManager {
public func setIdentityKeyPair(_ keyPair: ECKeyPair?, for identity: OWSIdentity, tx: DBWriteTransaction) {
// Under no circumstances may we *clear* our *ACI* identity key.
owsAssert(keyPair != nil || identity != .aci)
owsPrecondition(keyPair != nil || identity != .aci)
ownIdentityKeyValueStore.setObject(keyPair, key: identity.persistenceKey, transaction: tx)
}

View File

@ -15,7 +15,7 @@ public class StickerPackInfo: MTLModel {
@objc
public init(packId: Data, packKey: Data) {
owsAssert(!packId.isEmpty && packKey.count == StickerManager.packKeyLength)
owsPrecondition(!packId.isEmpty && packKey.count == StickerManager.packKeyLength)
self.packId = packId
self.packKey = packKey

View File

@ -31,8 +31,8 @@ public class SMKUDAccessKey: NSObject {
/// Used to compose multiple Unidentified-Access-Keys for the multiRecipient endpoint
public static func ^ (lhs: SMKUDAccessKey, rhs: SMKUDAccessKey) -> SMKUDAccessKey {
owsAssert(lhs.keyData.count == SMKUDAccessKey.kUDAccessKeyLength)
owsAssert(rhs.keyData.count == SMKUDAccessKey.kUDAccessKeyLength)
owsPrecondition(lhs.keyData.count == SMKUDAccessKey.kUDAccessKeyLength)
owsPrecondition(rhs.keyData.count == SMKUDAccessKey.kUDAccessKeyLength)
let xoredBytes = zip(lhs.keyData, rhs.keyData).map(^)
return .init(keyData: Data(xoredBytes))

View File

@ -16,7 +16,7 @@ class MockOutgoingCallEventSyncMessageManager: OutgoingCallEventSyncMessageManag
callEventTimestamp: UInt64,
tx: DBWriteTransaction
) {
owsAssert(expectedCallEvent == callEvent)
owsPrecondition(expectedCallEvent == callEvent)
syncMessageSendCount += 1
}
@ -26,7 +26,7 @@ class MockOutgoingCallEventSyncMessageManager: OutgoingCallEventSyncMessageManag
callEvent: CallEvent,
tx: DBWriteTransaction
) {
owsAssert(expectedCallEvent == callEvent)
owsPrecondition(expectedCallEvent == callEvent)
syncMessageSendCount += 1
}
}

View File

@ -40,7 +40,7 @@ class RESTNetworkManager {
let isUdRequest = request.isUDRequest
let label = isUdRequest ? "UD request" : "Non-UD request"
if (isUdRequest) {
owsAssert(!request.shouldHaveAuthorizationHeaders)
owsPrecondition(!request.shouldHaveAuthorizationHeaders)
}
Logger.info("Making \(label): \(request)")

View File

@ -10,7 +10,7 @@ public enum AccountAttributesRequestFactory {
/// If you are updating capabilities for a secondary device, use `updateLinkedDeviceCapabilitiesRequest` instead
public static func updatePrimaryDeviceAttributesRequest(_ attributes: AccountAttributes) -> TSRequest {
owsAssert(
owsPrecondition(
DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isPrimaryDevice ?? true,
"Trying to set primary device attributes from secondary/linked device"
)
@ -36,7 +36,7 @@ public enum AccountAttributesRequestFactory {
_ capabilities: AccountAttributes.Capabilities,
tsAccountManager: TSAccountManager
) -> TSRequest {
owsAssert(
owsPrecondition(
(tsAccountManager.registrationStateWithMaybeSneakyTransaction.isPrimaryDevice ?? false).negated,
"Trying to set seconday device attributes from primary device"
)

View File

@ -1457,7 +1457,7 @@ internal class OWSChatConnectionWithLibSignalShadowing: OWSChatConnectionUsingSS
}
internal init(libsignalNet: Net, type: OWSChatConnectionType, appExpiry: AppExpiry, db: DB, shadowingFrequency: Double) {
owsAssert((0.0...1.0).contains(shadowingFrequency))
owsPrecondition((0.0...1.0).contains(shadowingFrequency))
self.libsignalNet = libsignalNet
self.chatService = Self.makeChatService(libsignalNet: libsignalNet)
self._shadowingFrequency = shadowingFrequency
@ -1487,7 +1487,7 @@ internal class OWSChatConnectionWithLibSignalShadowing: OWSChatConnectionUsingSS
}
internal func updateShadowingFrequency(_ newFrequency: Double) {
owsAssert((0.0...1.0).contains(newFrequency))
owsPrecondition((0.0...1.0).contains(newFrequency))
serialQueue.async {
self.shadowingFrequency = newFrequency
}

View File

@ -85,7 +85,7 @@ final class WebSocketPromise: SSKWebSocketDelegate {
func waitForResponse() -> Promise<Data> {
let (promise, future) = Promise<Data>.pending()
updateState { state in
owsAssert(state.waitingState == nil)
owsPrecondition(state.waitingState == nil)
state.waitingState = .waitingForResponse(future)
}
return promise
@ -107,7 +107,7 @@ final class WebSocketPromise: SSKWebSocketDelegate {
func waitForAllResponses() -> Promise<[Data]> {
let (promise, future) = Promise<[Data]>.pending()
updateState { state in
owsAssert(state.waitingState == nil)
owsPrecondition(state.waitingState == nil)
state.waitingState = .waitingForAllResponses(future)
}
return promise

View File

@ -660,7 +660,7 @@ public class NotificationPresenterImpl: NotificationPresenter {
guard previewType == .namePreview else {
return
}
owsAssert(Self.shouldShowActions(for: previewType))
owsPrecondition(Self.shouldShowActions(for: previewType))
let senderName = contactManager.displayName(for: reaction.reactor, tx: transaction).resolvedValue()

View File

@ -89,14 +89,14 @@ NS_ASSUME_NONNULL_BEGIN
#endif
// Like OWSAssertDebug, but will fail in production, terminating the app
#define OWSAssert(X) \
#define OWSPrecondition(X) \
do { \
if (!(X)) { \
OWSFail(@"Assertion failed: %s", CONVERT_EXPR_TO_STRING(X)); \
} \
} while (NO)
#define OWSCAssert(X) \
#define OWSCPrecondition(X) \
do { \
if (!(X)) { \
OWSCFail(@"Assertion failed: %s", CONVERT_EXPR_TO_STRING(X)); \
@ -156,19 +156,19 @@ __attribute__((annotate("returns_localized_nsstring"))) static inline NSString *
#define ows_add_overflow(a, b, resultRef) \
do { \
BOOL _didOverflow = __builtin_add_overflow(a, b, resultRef); \
OWSAssert(!_didOverflow); \
OWSPrecondition(!_didOverflow); \
} while (NO)
#define ows_sub_overflow(a, b, resultRef) \
do { \
BOOL _didOverflow = __builtin_sub_overflow(a, b, resultRef); \
OWSAssert(!_didOverflow); \
OWSPrecondition(!_didOverflow); \
} while (NO)
#define ows_mul_overflow(a, b, resultRef) \
do { \
BOOL _didOverflow = __builtin_mul_overflow(a, b, resultRef); \
OWSAssert(!_didOverflow); \
OWSPrecondition(!_didOverflow); \
} while (NO)
NS_ASSUME_NONNULL_END

View File

@ -76,15 +76,18 @@ public func owsAssertDebug(
}
}
/// Like `Swift.precondition(_:)`, this will trap if `condition` evaluates to
/// `false`. Also performs additional logging before terminating the process.
/// See `owsFail(_:)` for more information about logging.
@inlinable
public func owsAssert(
_ condition: Bool,
public func owsPrecondition(
_ condition: @autoclosure () -> Bool,
_ message: @autoclosure () -> String = String(),
file: String = #fileID,
function: String = #function,
line: Int = #line
) {
if !condition {
if !condition() {
let message: String = message()
owsFail(message.isEmpty ? "Assertion failed." : message, file: file, function: function, line: line)
}

View File

@ -22,8 +22,8 @@ NS_ASSUME_NONNULL_BEGIN
}
NSData *copy = [randomBytes copy];
OWSAssert(copy != nil);
OWSAssert(copy.length == numberBytes);
OWSPrecondition(copy != nil);
OWSPrecondition(copy.length == numberBytes);
return copy;
}

View File

@ -40,7 +40,7 @@ void SCKRaiseIfExceptionWrapperError(NSError *_Nullable error)
if (error && [error.domain isEqualToString:SCKExceptionWrapperErrorDomain]
&& error.code == SCKExceptionWrapperErrorThrown) {
NSException *_Nullable exception = error.userInfo[SCKExceptionWrapperUnderlyingExceptionKey];
OWSCAssert(exception);
OWSCPrecondition(exception);
@throw exception;
}
}

View File

@ -15,7 +15,7 @@ public class SSKEnvironment: NSObject {
public static var shared: SSKEnvironment { _shared! }
public static func setShared(_ env: SSKEnvironment, isRunningTests: Bool) {
owsAssert(_shared == nil || isRunningTests)
owsPrecondition(_shared == nil || isRunningTests)
_shared = env
}

View File

@ -45,7 +45,7 @@ NS_ASSUME_NONNULL_BEGIN
}
NSData *data = [NSData dataWithContentsOfFile:path];
OWSAssert(data.length > 0);
OWSPrecondition(data.length > 0);
return data;
}
@ -62,7 +62,7 @@ NS_ASSUME_NONNULL_BEGIN
{
NSData *certificateData = [self dataFromCertificateFileForService:service];
SecCertificateRef certRef = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(certificateData));
OWSAssert(certRef);
OWSPrecondition(certRef);
return certRef;
}

View File

@ -34,8 +34,8 @@ static NSString *const kCoderIndex = @"kCoderIndex";
- (instancetype)initWithData:(NSData *)chainKey index:(int)index
{
OWSAssert(chainKey.length == 32);
OWSAssert(index >= 0);
OWSPrecondition(chainKey.length == 32);
OWSPrecondition(index >= 0);
self = [super init];

View File

@ -39,9 +39,9 @@ static NSString *const kCoderMessageKeysIndex = @"kCoderMessageKeysIndex";
- (instancetype)initWithCipherKey:(NSData *)cipherKey macKey:(NSData *)macKey iv:(NSData *)data index:(int)index
{
OWSAssert(cipherKey);
OWSAssert(macKey);
OWSAssert(data);
OWSPrecondition(cipherKey);
OWSPrecondition(macKey);
OWSPrecondition(data);
self = [super init];

View File

@ -42,8 +42,8 @@ static NSString *const kCoderMessageKeys = @"kCoderMessageKeys";
- (instancetype)initWithChainKey:(LegacyChainKey *)chainKey senderRatchetKey:(NSData *)senderRatchet
{
OWSAssert(chainKey);
OWSAssert(senderRatchet);
OWSPrecondition(chainKey);
OWSPrecondition(senderRatchet);
self = [super init];

View File

@ -35,7 +35,7 @@ static NSString *const kCoderData = @"kCoderData";
{
self = [super init];
OWSAssert(data.length == 32);
OWSPrecondition(data.length == 32);
if (self) {
_keyData = data;

View File

@ -41,8 +41,8 @@ static NSString *const kCoderSenderRatchet = @"kCoderSenderRatchet";
{
self = [super init];
OWSAssert(chainKey.key.length == 32);
OWSAssert(keyPair);
OWSPrecondition(chainKey.key.length == 32);
OWSPrecondition(keyPair);
if (self) {
_chainKey = chainKey;

View File

@ -22,7 +22,7 @@ static NSString *const kCoderBaseKey = @"kCoderBaseKey";
- (instancetype)initWithBaseKey:(NSData *)baseKey preKeyId:(int)preKeyId signedPreKeyId:(int)signedPrekeyId
{
OWSAssert(baseKey);
OWSPrecondition(baseKey);
self = [super init];
if (self) {
@ -143,8 +143,8 @@ static NSString *const kCoderPendingPrekey = @"kCoderPendingPrekey";
- (void)setSenderChain:(ECKeyPair *)senderRatchetKeyPair chainKey:(LegacyChainKey *)chainKey
{
OWSAssert(senderRatchetKeyPair);
OWSAssert(chainKey);
OWSPrecondition(senderRatchetKeyPair);
OWSPrecondition(chainKey);
self.sendingChain = [[LegacySendingChain alloc] initWithChainKey:chainKey
senderRatchetKeyPair:senderRatchetKeyPair];
@ -157,7 +157,7 @@ static NSString *const kCoderPendingPrekey = @"kCoderPendingPrekey";
- (void)setUnacknowledgedPreKeyMessage:(int)preKeyId signedPreKey:(int)signedPreKeyId baseKey:(NSData *)baseKey
{
OWSAssert(baseKey);
OWSPrecondition(baseKey);
LegacyPendingPreKey *pendingPreKey = [[LegacyPendingPreKey alloc] initWithBaseKey:baseKey
preKeyId:preKeyId

View File

@ -21,7 +21,7 @@ static NSString *const kCoderCreatedAt = @"kCoderCreatedAt";
- (instancetype)initWithId:(int)identifier keyPair:(ECKeyPair *)keyPair createdAt:(NSDate *)createdAt
{
OWSAssert(keyPair);
OWSPrecondition(keyPair);
self = [super init];

View File

@ -90,7 +90,7 @@ NSString *const kLastPreKeyRotationDate = @"lastKeyRotationDate";
- (SignedPreKeyRecord *)generateRandomSignedRecord
{
ECKeyPair *_Nullable identityKeyPair = [OWSIdentityManagerObjCBridge identityKeyPairForIdentity:_identity];
OWSAssert(identityKeyPair);
OWSPrecondition(identityKeyPair);
return [SSKSignedPreKeyStore generateSignedPreKeyWithSignedBy:identityKeyPair];
}

View File

@ -481,7 +481,7 @@ public extension DatabaseRecovery {
from: SDSDatabaseStorage,
to: SDSDatabaseStorage
) -> TableCopyResult {
owsAssert(SqliteUtil.isSafe(sqlName: tableName))
owsPrecondition(SqliteUtil.isSafe(sqlName: tableName))
do {
return try from.readThrows { fromTransaction -> TableCopyResult in
@ -554,7 +554,7 @@ public extension DatabaseRecovery {
}
private static func getColumnNames(db: Database, tableName: String) throws -> [String] {
owsAssert(SqliteUtil.isSafe(sqlName: tableName))
owsPrecondition(SqliteUtil.isSafe(sqlName: tableName))
var result = [String]()
let cursor = try Row.fetchCursor(db, sql: "PRAGMA table_info(\(tableName))")
@ -568,9 +568,9 @@ public extension DatabaseRecovery {
}
private static func insertSql(tableName: String, columnNames: [String]) -> String {
owsAssert(SqliteUtil.isSafe(sqlName: tableName))
owsPrecondition(SqliteUtil.isSafe(sqlName: tableName))
for columnName in columnNames {
owsAssert(SqliteUtil.isSafe(sqlName: columnName))
owsPrecondition(SqliteUtil.isSafe(sqlName: columnName))
}
let columnNamesSql = columnNames.joined(separator: ", ")

View File

@ -327,8 +327,8 @@ extension GRDBDatabaseStorageAdapter {
// We're already in an unexpected (but recoverable) state. However if the currently active transfer
// path is a file or a non-empty directory, we're too close to losing data and we should fail.
if FileManager.default.fileExists(atPath: transferDatabaseDir.path, isDirectory: &isDirectory) {
owsAssert(isDirectory.boolValue)
owsAssert(try! FileManager.default.contentsOfDirectory(atPath: transferDatabaseDir.path).isEmpty)
owsPrecondition(isDirectory.boolValue)
owsPrecondition(try! FileManager.default.contentsOfDirectory(atPath: transferDatabaseDir.path).isEmpty)
}
OWSFileSystem.deleteFileIfExists(transferDatabaseDir.path)
clearTransferDirectory()
@ -346,7 +346,7 @@ extension GRDBDatabaseStorageAdapter {
}
public static func promoteTransferDirectoryToPrimary() {
owsAssert(CurrentAppContext().isMainApp, "Only the main app can swap databases")
owsPrecondition(CurrentAppContext().isMainApp, "Only the main app can swap databases")
// Ordering matters here. We should be able to crash and recover without issue
// A prior run may have already performed the swap but crashed, so we should not expect a transfer folder
@ -904,7 +904,7 @@ public struct GRDBKeyFetcher {
/// - Note: Will fatally assert if not running in a debug or test build.
/// - Returns: The key data, if available.
public func debugOnly_keyData() -> Data? {
owsAssert(DebugFlags.internalSettings)
owsPrecondition(DebugFlags.internalSettings)
return try? fetchData()
}
}

View File

@ -34,7 +34,7 @@ NS_ASSUME_NONNULL_BEGIN
id _Nullable value = [self.keyValueStore getObjectForKey:key transaction:transaction];
OWSAssert(!value || [value isKindOfClass:klass]);
OWSPrecondition(!value || [value isKindOfClass:klass]);
return value;
}
@ -44,7 +44,7 @@ NS_ASSUME_NONNULL_BEGIN
transaction:(SDSAnyWriteTransaction *)transaction
{
OWSAssertDebug(key.length > 0);
OWSAssert([object isKindOfClass:klass]);
OWSPrecondition([object isKindOfClass:klass]);
[self.keyValueStore setObject:object key:key transaction:transaction];
}

View File

@ -26,7 +26,7 @@ public extension Paypal {
)
session.presentationContextProvider = presentationContext
owsAssert(
owsPrecondition(
session.start(),
"[Donations] Failed to start PayPal authentication session. Was it set up correctly?"
)

View File

@ -47,7 +47,7 @@ public struct ReceiptCredentialRequestError: Codable, Equatable {
amount: FiatMoney,
paymentMethod: DonationPaymentMethod
) {
owsAssert(
owsPrecondition(
chargeFailureCodeIfPaymentFailed == nil || errorCode == .paymentFailed,
"Charge failure must only be populated if the error code is payment failed!"
)

View File

@ -642,7 +642,7 @@ public class SubscriptionManagerImpl: NSObject {
errorCode: ReceiptCredentialRequestError.ErrorCode,
chargeFailureCodeIfPaymentFailed: String? = nil
) {
owsAssert(
owsPrecondition(
chargeFailureCodeIfPaymentFailed == nil || errorCode == .paymentFailed,
"Must only provide a charge failure if payment failed!"
)

View File

@ -147,7 +147,7 @@ public struct MrEnclave: Equatable {
// This is a constant -- it should never fail to parse.
self.dataValue = Data.data(fromHex: self.stringValue)!
// All of our MrEnclave values are currently 32 bytes.
owsAssert(self.dataValue.count == 32)
owsPrecondition(self.dataValue.count == 32)
}
public static func == (lhs: Self, rhs: Self) -> Bool {

View File

@ -54,7 +54,7 @@ public class MockSSKEnvironment: NSObject {
backgroundScheduler: SyncScheduler(),
mainScheduler: SyncScheduler()
)
owsAssert(finalContinuation.isSealed)
owsPrecondition(finalContinuation.isSealed)
}
@objc

View File

@ -116,7 +116,7 @@ public struct TestProtocolRunner {
recipientClient: TestSignalClient,
sender: ProtocolAddress,
context: StoreContext) throws -> Data {
owsAssert(cipherMessage.messageType == .whisper, "only bare SignalMessages are supported")
owsPrecondition(cipherMessage.messageType == .whisper, "only bare SignalMessages are supported")
let message = try SignalMessage(bytes: cipherMessage.serialize())
return Data(try signalDecrypt(message: message,
from: sender,

View File

@ -37,7 +37,7 @@ public struct Currency {
shouldSort: Bool
) -> [Info] {
#if TESTABLE_BUILD
owsAssert(Array(codes).count == Set(codes).count)
owsPrecondition(Array(codes).count == Set(codes).count)
#endif
var infos = codes.compactMap { Info(code: $0, ignoreMissingName: ignoreMissingNames) }
if shouldSort { infos.sort { $0.name < $1.name } }

View File

@ -183,7 +183,7 @@ public class PngChunker {
extension Data {
func asPngUInt32() throws -> UInt32 {
owsAssert(count == 4)
owsPrecondition(count == 4)
var result: UInt32 = 0
for (i, byte) in reversed().enumerated() {
result += UInt32(byte) * (1 << (8 * i))

View File

@ -313,7 +313,7 @@ class ModelReadCache<KeyType: Hashable & Equatable, ValueType>: Dependencies, Ca
func add(lease: ModelReadCacheSizeLease) {
performSync {
// It's a bug to add an already-added lease.
owsAssert(!leases.contains(lease))
owsPrecondition(!leases.contains(lease))
leases.add(lease)
updateMaxSize()

View File

@ -11,7 +11,7 @@ NS_ASSUME_NONNULL_BEGIN
+ (NSData *)join:(NSArray<NSData *> *)datas
{
OWSAssert(datas);
OWSPrecondition(datas);
NSMutableData *result = [NSMutableData new];
for (NSData *data in datas) {

View File

@ -100,7 +100,7 @@ NS_ASSUME_NONNULL_BEGIN
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSArray<NSString *> *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
OWSAssert(paths.count >= 1);
OWSPrecondition(paths.count >= 1);
result = paths[0];
});
return result;
@ -267,7 +267,7 @@ NSString *OWSTemporaryDirectory(void)
NSString *dirName = [NSString stringWithFormat:@"ows_temp_%@", NSUUID.UUID.UUIDString];
dirPath = [NSTemporaryDirectory() stringByAppendingPathComponent:dirName];
BOOL success = [OWSFileSystem ensureDirectoryExists:dirPath fileProtectionType:NSFileProtectionComplete];
OWSCAssert(success);
OWSCPrecondition(success);
});
return dirPath;
}
@ -277,7 +277,7 @@ NSString *OWSTemporaryDirectoryAccessibleAfterFirstAuth(void)
NSString *dirPath = NSTemporaryDirectory();
BOOL success = [OWSFileSystem ensureDirectoryExists:dirPath
fileProtectionType:NSFileProtectionCompleteUntilFirstUserAuthentication];
OWSCAssert(success);
OWSCPrecondition(success);
return dirPath;
}

View File

@ -30,7 +30,7 @@ public struct OrderedDictionary<KeyType: Hashable, ValueType> {
}
public mutating func insert(key: KeyType, at index: Int, value: ValueType) {
owsAssert(keyValueMap[key] == nil, "Key already in dictionary: \(key)")
owsPrecondition(keyValueMap[key] == nil, "Key already in dictionary: \(key)")
owsAssertDebug(!orderedKeys.contains(key), "Unexpected duplicate key in key list: \(key)")
keyValueMap[key] = value
@ -125,7 +125,7 @@ extension OrderedDictionary: RandomAccessCollection {
public var endIndex: Int { self.orderedKeys.count }
public subscript(position: Int) -> (key: KeyType, value: ValueType) {
owsAssert(indices.contains(position))
owsPrecondition(indices.contains(position))
let key = orderedKeys[position]
guard let value = keyValueMap[key] else {
owsFail("Missing value")

View File

@ -154,7 +154,7 @@ public enum SqliteUtil {
ftsTableName: String,
compareToExternalContentTable: Bool
) throws -> IntegrityCheckResult {
owsAssert(SqliteUtil.isSafe(sqlName: ftsTableName))
owsPrecondition(SqliteUtil.isSafe(sqlName: ftsTableName))
let sql: String
if compareToExternalContentTable {
@ -187,7 +187,7 @@ public enum SqliteUtil {
///
/// [rebuild command]: https://www.sqlite.org/fts5.html#the_rebuild_command
public static func rebuild(db: Database, ftsTableName: String) throws {
owsAssert(SqliteUtil.isSafe(sqlName: ftsTableName))
owsPrecondition(SqliteUtil.isSafe(sqlName: ftsTableName))
try db.execute(
sql: "INSERT INTO \(ftsTableName) (\(ftsTableName)) VALUES ('rebuild')"
@ -217,7 +217,7 @@ public enum SqliteUtil {
) throws -> MergeResult {
let totalChangesBefore = db.totalChangesCount
owsAssert(SqliteUtil.isSafe(sqlName: ftsTableName))
owsPrecondition(SqliteUtil.isSafe(sqlName: ftsTableName))
try db.execute(
sql: "INSERT INTO \(ftsTableName) (\(ftsTableName), rank) VALUES ('merge', ?)",
arguments: [isFirstBatch ? -numberOfPages : numberOfPages]

View File

@ -18,7 +18,7 @@ final class SignedPreKeyDeletionTests: SSKBaseTest {
var justUploadedRecord: SignedPreKeyRecord!
for daysAgo in stride(from: 0, through: maxDaysAgo, by: 5) {
let secondsAgo: TimeInterval = Double(daysAgo - maxDaysAgo) * kDayInterval
owsAssert(secondsAgo <= 0, "Time in past must be negative!")
owsPrecondition(secondsAgo <= 0, "Time in past must be negative!")
let record = SignedPreKeyRecord(
id: Int32(daysAgo),
@ -62,7 +62,7 @@ final class SignedPreKeyDeletionTests: SSKBaseTest {
// All these keys will be considered "old", since they were created
// more than 30 days ago.
let secondsAgo: TimeInterval = Double(idx - 40) * kDayInterval
owsAssert(secondsAgo <= 0, "Time in past must be negative!")
owsPrecondition(secondsAgo <= 0, "Time in past must be negative!")
let record = SignedPreKeyRecord(
id: Int32(idx),

View File

@ -38,7 +38,7 @@ final class DisappearingMessageFinderTest: SSKBaseTest {
write { transaction -> TSIncomingMessage in
// It only makes sense to "mark as read" if expiration hasn't started,
// since we don't start expiration for unread incoming messages.
owsAssert(!markAsRead || expireStartedAt == 0)
owsPrecondition(!markAsRead || expireStartedAt == 0)
let thread = self.thread(with: transaction)

View File

@ -371,7 +371,7 @@ final class DatabaseRecoveryTest: SSKBaseTest {
let db = transaction.unwrapGrdbRead.database
let sql = "SELECT name FROM sqlite_schema WHERE type IS 'table'"
let allTableNames = Set((try? String.fetchAll(db, sql: sql)) ?? [])
owsAssert(!allTableNames.isEmpty, "No tables were found!")
owsPrecondition(!allTableNames.isEmpty, "No tables were found!")
let tableNamesToSkip: Set<String> = ["grdb_migrations", "sqlite_sequence"]
return allTableNames.filter { tableName in

View File

@ -207,7 +207,7 @@ public class ShareViewController: UIViewController, ShareViewDelegate, SAEFailed
private func setAppIsReady() {
Logger.debug("")
AssertIsOnMainThread()
owsAssert(!AppReadiness.isAppReady)
owsPrecondition(!AppReadiness.isAppReady)
// We don't need to use LaunchJobs in the SAE.

View File

@ -38,7 +38,7 @@ class ContactShareFieldBase<ContactFieldType: OWSContactField>: ContactShareFiel
class ContactSharePhoneNumber: ContactShareFieldBase<OWSContactPhoneNumber> {
override func applyToContact(contact: ContactShareDraft) {
owsAssert(isIncluded)
owsPrecondition(isIncluded)
var values = [OWSContactPhoneNumber]()
values += contact.phoneNumbers
@ -50,7 +50,7 @@ class ContactSharePhoneNumber: ContactShareFieldBase<OWSContactPhoneNumber> {
class ContactShareEmail: ContactShareFieldBase<OWSContactEmail> {
override func applyToContact(contact: ContactShareDraft) {
owsAssert(isIncluded)
owsPrecondition(isIncluded)
var values = [OWSContactEmail]()
values += contact.emails
@ -62,7 +62,7 @@ class ContactShareEmail: ContactShareFieldBase<OWSContactEmail> {
class ContactShareAddress: ContactShareFieldBase<OWSContactAddress> {
override func applyToContact(contact: ContactShareDraft) {
owsAssert(isIncluded)
owsPrecondition(isIncluded)
var values = [OWSContactAddress]()
values += contact.addresses
@ -94,7 +94,7 @@ class OWSContactAvatar: NSObject, OWSContactField {
class ContactShareAvatarField: ContactShareFieldBase<OWSContactAvatar> {
override func applyToContact(contact: ContactShareDraft) {
owsAssert(isIncluded)
owsPrecondition(isIncluded)
contact.avatarImageData = value.avatarData
contact.existingAvatarAttachment = value.existingAttachment

View File

@ -201,7 +201,7 @@ public class ContactShareViewController: OWSTableViewController2 {
}
let filteredContactShare = filteredContactShare()
owsAssert(filteredContactShare.ows_isValid)
owsPrecondition(filteredContactShare.ows_isValid)
shareDelegate.contactShareViewController(self, didApproveContactShare: filteredContactShare)
}

View File

@ -74,7 +74,7 @@ class DeleteSystemContactViewController: OWSTableViewController2 {
// This screen is for primary devices only. If a non primary
// manages to get here bad things could happen.
owsAssert(DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegisteredPrimaryDevice)
owsPrecondition(DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegisteredPrimaryDevice)
self.navigationItem.leftBarButtonItem = .cancelButton(dismissingFrom: self)
}