RPCWriter+Serialize.swift 1.8 KB

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