RPCWriter+Map.swift 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 10.15, iOS 13, tvOS 13, watchOS 6, *)
  17. @usableFromInline
  18. struct MapRPCWriter<
  19. Value: Sendable,
  20. Mapped: Sendable,
  21. Base: RPCWriterProtocol<Mapped>
  22. >: RPCWriterProtocol {
  23. @usableFromInline
  24. typealias Element = Value
  25. @usableFromInline
  26. let base: Base
  27. @usableFromInline
  28. let transform: @Sendable (Value) throws -> Mapped
  29. @inlinable
  30. init(base: Base, transform: @escaping @Sendable (Value) throws -> Mapped) {
  31. self.base = base
  32. self.transform = transform
  33. }
  34. @inlinable
  35. func write(_ element: Element) async throws {
  36. try await self.base.write(self.transform(element))
  37. }
  38. @inlinable
  39. func write(contentsOf elements: some Sequence<Value>) async throws {
  40. let transformed = try elements.lazy.map { try self.transform($0) }
  41. try await self.base.write(contentsOf: transformed)
  42. }
  43. }
  44. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  45. extension RPCWriter {
  46. @inlinable
  47. static func map<Mapped>(
  48. into writer: some RPCWriterProtocol<Mapped>,
  49. transform: @Sendable @escaping (Element) throws -> Mapped
  50. ) -> Self {
  51. let mapper = MapRPCWriter(base: writer, transform: transform)
  52. return RPCWriter(wrapping: mapper)
  53. }
  54. }