AsyncSequenceOfOne.swift 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  17. extension RPCAsyncSequence {
  18. /// Returns an ``RPCAsyncSequence`` containing just the given element.
  19. @inlinable
  20. static func one(_ element: Element) -> Self {
  21. let source = AsyncSequenceOfOne<Element, Failure>(result: .success(element))
  22. return RPCAsyncSequence(wrapping: source)
  23. }
  24. /// Returns an ``RPCAsyncSequence`` throwing the given error.
  25. @inlinable
  26. static func throwing(_ error: Failure) -> Self {
  27. let source = AsyncSequenceOfOne<Element, Failure>(result: .failure(error))
  28. return RPCAsyncSequence(wrapping: source)
  29. }
  30. }
  31. /// An `AsyncSequence` of a single value.
  32. @usableFromInline
  33. @available(macOS 10.15, iOS 13.0, tvOS 13, watchOS 6, *)
  34. struct AsyncSequenceOfOne<Element: Sendable, Failure: Error>: AsyncSequence, Sendable {
  35. @usableFromInline
  36. let result: Result<Element, Failure>
  37. @inlinable
  38. init(result: Result<Element, Failure>) {
  39. self.result = result
  40. }
  41. @inlinable
  42. func makeAsyncIterator() -> AsyncIterator {
  43. AsyncIterator(result: self.result)
  44. }
  45. @usableFromInline
  46. struct AsyncIterator: AsyncIteratorProtocol {
  47. @usableFromInline
  48. private(set) var result: Result<Element, Failure>?
  49. @inlinable
  50. init(result: Result<Element, Failure>) {
  51. self.result = result
  52. }
  53. @inlinable
  54. mutating func next(
  55. isolation actor: isolated (any Actor)?
  56. ) async throws(Failure) -> Element? {
  57. guard let result = self.result else { return nil }
  58. self.result = nil
  59. return try result.get()
  60. }
  61. @inlinable
  62. mutating func next() async throws -> Element? {
  63. try await self.next(isolation: nil)
  64. }
  65. }
  66. }