RPCWriter+Map.swift 1.7 KB

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