RPCWriter+MessageToRPCResponsePart.swift 1.9 KB

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