2
0

RPCWriter+MessageToRPCResponsePart.swift 1.8 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 MessageToRPCResponsePartWriter<
  18. Serializer: MessageSerializer
  19. >: RPCWriterProtocol where Serializer.Message: Sendable {
  20. @usableFromInline
  21. typealias Element = Serializer.Message
  22. @usableFromInline
  23. let base: RPCWriter<RPCResponsePart>
  24. @usableFromInline
  25. let serializer: Serializer
  26. @inlinable
  27. init(serializer: Serializer, base: some RPCWriterProtocol<RPCResponsePart>) {
  28. self.serializer = serializer
  29. self.base = RPCWriter(wrapping: base)
  30. }
  31. @inlinable
  32. func write(_ element: Element) async throws {
  33. try await self.base.write(.message(self.serializer.serialize(element)))
  34. }
  35. @inlinable
  36. func write(contentsOf elements: some Sequence<Serializer.Message>) async throws {
  37. let requestParts = try elements.map { message -> RPCResponsePart in
  38. .message(try self.serializer.serialize(message))
  39. }
  40. try await self.base.write(contentsOf: requestParts)
  41. }
  42. }
  43. extension RPCWriter {
  44. @inlinable
  45. static func serializingToRPCResponsePart(
  46. into writer: some RPCWriterProtocol<RPCResponsePart>,
  47. with serializer: some MessageSerializer<Element>
  48. ) -> Self {
  49. return RPCWriter(wrapping: MessageToRPCResponsePartWriter(serializer: serializer, base: writer))
  50. }
  51. }