|
| 1 | +// |
| 2 | +// This source file is part of the Swift.org open source project |
| 3 | +// |
| 4 | +// Copyright (c) 2025 Apple Inc. and the Swift project authors |
| 5 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 6 | +// |
| 7 | +// See https://swift.org/LICENSE.txt for license information |
| 8 | +// See https://swift.org/CONTRIBUTORS.txt for Swift project authors |
| 9 | +// |
| 10 | + |
| 11 | +/// A type whose instances can run a series of work items in strict order. |
| 12 | +/// |
| 13 | +/// When a work item is scheduled on an instance of this type, it runs after any |
| 14 | +/// previously-scheduled work items. If it suspends, subsequently-scheduled work |
| 15 | +/// items do not start running; they must wait until the suspended work item |
| 16 | +/// either returns or throws an error. |
| 17 | +final actor Serializer { |
| 18 | + /// The number of scheduled work items, including (possibly) the one currently |
| 19 | + /// running. |
| 20 | + private var scheduledCount = 0 |
| 21 | + |
| 22 | + /// Continuations for any scheduled work items that haven't started yet. |
| 23 | + private var continuations = [CheckedContinuation<Void, Never>]() |
| 24 | + |
| 25 | + /// Run a work item serially after any previously-scheduled work items. |
| 26 | + /// |
| 27 | + /// - Parameters: |
| 28 | + /// - workItem: A closure to run. |
| 29 | + /// |
| 30 | + /// - Returns: Whatever is returned from `workItem`. |
| 31 | + /// |
| 32 | + /// - Throws: Whatever is thrown by `workItem`. |
| 33 | + func run<R>(_ workItem: @Sendable @isolated(any) () async throws -> sending R) async rethrows -> R { |
| 34 | + scheduledCount += 1 |
| 35 | + defer { |
| 36 | + // Resume the next scheduled closure. |
| 37 | + if !continuations.isEmpty { |
| 38 | + let continuation = continuations.removeFirst() |
| 39 | + continuation.resume() |
| 40 | + } |
| 41 | + |
| 42 | + scheduledCount -= 1 |
| 43 | + } |
| 44 | + |
| 45 | + await withCheckedContinuation { continuation in |
| 46 | + if scheduledCount == 1 { |
| 47 | + // Nothing else was scheduled, so we can resume immediately. |
| 48 | + continuation.resume() |
| 49 | + } else { |
| 50 | + // Something was scheduled, so add the continuation to the list. When it |
| 51 | + // resumes, we can run. |
| 52 | + continuations.append(continuation) |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + return try await workItem() |
| 57 | + } |
| 58 | +} |
| 59 | + |
0 commit comments