RPCWriter+MessageToRPCResponsePart.swift 2.0 KB

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