-
Notifications
You must be signed in to change notification settings - Fork 162
/
Copy pathDeadline.swift
60 lines (55 loc) · 1.85 KB
/
Deadline.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Async Algorithms open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public struct TimeoutError<C: Clock>: Error {
public let deadline: C.Instant
public let clock: C
public init(_ deadline: C.Instant, _ clock: C) {
self.deadline = deadline
self.clock = clock
}
}
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public func withDeadline<C: Clock, T: Sendable>(
_ deadline: C.Instant,
clock: C,
_ operation: @Sendable () async throws -> T
) async throws -> T {
return try await withoutActuallyEscaping(operation) { operation in
try await withThrowingTaskGroup(of: T.self) { group in
group.addTask(operation: operation)
group.addTask {
try await Task.sleep(until: deadline, clock: clock)
throw TimeoutError(deadline, clock)
}
defer { group.cancelAll() }
return try await group.next()!
}
}
}
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public func withTimeout<C: Clock, T: Sendable>(
in duration: C.Duration,
clock: C,
_ operation: @Sendable () async throws -> T
) async throws -> T {
try await withDeadline(
clock.now.advanced(by: duration),
clock: clock,
operation)
}
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public func withTimeout<T: Sendable>(
in duration: Duration,
_ operation: @Sendable () async throws -> T
) async throws -> T {
try await withTimeout(in: duration, clock: .continuous, operation)
}