From 83abfb34dc2bf4f3605b67d73573e2617bb246ba Mon Sep 17 00:00:00 2001 From: Nikita Bobko Date: Sun, 8 Mar 2026 20:30:39 +0100 Subject: [PATCH] Refactor: create UniqueToken class Motivation: I'm gonna use this class in more places --- .../AppBundle/util/AwaitableOneTimeBroadcastLatch.swift | 9 ++++----- Sources/AppBundle/util/UniqueToken.swift | 6 ++++++ 2 files changed, 10 insertions(+), 5 deletions(-) create mode 100644 Sources/AppBundle/util/UniqueToken.swift diff --git a/Sources/AppBundle/util/AwaitableOneTimeBroadcastLatch.swift b/Sources/AppBundle/util/AwaitableOneTimeBroadcastLatch.swift index 09c751fc..faa8196a 100644 --- a/Sources/AppBundle/util/AwaitableOneTimeBroadcastLatch.swift +++ b/Sources/AppBundle/util/AwaitableOneTimeBroadcastLatch.swift @@ -1,16 +1,15 @@ import Common +import Foundation actor AwaitableOneTimeBroadcastLatch { private var done = false - private var awaiters: [Int: Nullable>] = [:] - private var counter = Int.min + private var awaiters: [UniqueToken: Nullable>] = [:] func await() async throws { try checkCancellation() if done { return } - let id = counter - counter += 1 + let id = UniqueToken() try await withTaskCancellationHandler { try await withCheckedThrowingContinuation { (cont: CheckedContinuation<(), any Error>) in if let awaiter = awaiters.removeValue(forKey: id) { @@ -27,7 +26,7 @@ actor AwaitableOneTimeBroadcastLatch { } } - private func cancel(id: Int) { + private func cancel(id: UniqueToken) { if let awaiter = awaiters.removeValue(forKey: id) { awaiter.valueOrNil.orDie().resume(throwing: CancellationError()) } else if !done { diff --git a/Sources/AppBundle/util/UniqueToken.swift b/Sources/AppBundle/util/UniqueToken.swift new file mode 100644 index 00000000..0e29a37c --- /dev/null +++ b/Sources/AppBundle/util/UniqueToken.swift @@ -0,0 +1,6 @@ +final class UniqueToken: Equatable, Hashable, CustomStringConvertible, Sendable { + private let hash = Int.random(in: Int.min ... Int.max) + static func == (lhs: UniqueToken, rhs: UniqueToken) -> Bool { lhs === rhs } + func hash(into hasher: inout Hasher) { hasher.combine(hash) } + var description: String { "UniqueToken(\(hash))" } +} -- 2.51.2