RPCWriter+Map.swift 1.7 KB

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