RPCWriter+Map.swift 1.6 KB

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