RPCAsyncSequence.swift 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * Copyright 2023, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. /// A type-erasing `AsyncSequence`.
  17. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  18. public struct RPCAsyncSequence<Element, Failure: Error>: AsyncSequence, @unchecked Sendable {
  19. // @unchecked Sendable is required because 'any' doesn't support composition with primary
  20. // associated types. (see: https://github.com/swiftlang/swift/issue/63877)
  21. //
  22. // To work around that limitation the 'init' requires that the async sequence being wrapped
  23. // is 'Sendable' but that constraint must be dropped internally. This is safe, the compiler just
  24. // can't prove it.
  25. @usableFromInline
  26. let _wrapped: any AsyncSequence<Element, Failure>
  27. /// Creates an ``RPCAsyncSequence`` by wrapping another `AsyncSequence`.
  28. @inlinable
  29. public init<Source: AsyncSequence<Element, Failure>>(
  30. wrapping other: Source
  31. ) where Source: Sendable {
  32. self._wrapped = other
  33. }
  34. @inlinable
  35. public func makeAsyncIterator() -> AsyncIterator {
  36. AsyncIterator(wrapping: self._wrapped.makeAsyncIterator())
  37. }
  38. public struct AsyncIterator: AsyncIteratorProtocol {
  39. @usableFromInline
  40. private(set) var iterator: any AsyncIteratorProtocol<Element, Failure>
  41. @inlinable
  42. init(
  43. wrapping other: some AsyncIteratorProtocol<Element, Failure>
  44. ) {
  45. self.iterator = other
  46. }
  47. @inlinable
  48. public mutating func next(
  49. isolation actor: isolated (any Actor)?
  50. ) async throws(Failure) -> Element? {
  51. try await self.iterator.next(isolation: `actor`)
  52. }
  53. @inlinable
  54. public mutating func next() async throws -> Element? {
  55. try await self.next(isolation: nil)
  56. }
  57. }
  58. }
  59. @available(*, unavailable)
  60. extension RPCAsyncSequence.AsyncIterator: Sendable {}