Coding.swift 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * Copyright 2024, 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. public import GRPCCore
  17. public import SwiftProtobuf
  18. /// Serializes a Protobuf message into a sequence of bytes.
  19. public struct ProtobufSerializer<Message: SwiftProtobuf.Message>: GRPCCore.MessageSerializer {
  20. public init() {}
  21. /// Serializes a `Message` into a sequence of bytes.
  22. ///
  23. /// - Parameter message: The message to serialize.
  24. /// - Returns: An array of serialized bytes representing the message.
  25. @inlinable
  26. public func serialize<Bytes: GRPCContiguousBytes>(_ message: Message) throws -> Bytes {
  27. do {
  28. let adapter = try message.serializedBytes() as ContiguousBytesAdapter<Bytes>
  29. return adapter.bytes
  30. } catch let error {
  31. throw RPCError(
  32. code: .invalidArgument,
  33. message: "Can't serialize message of type \(type(of: message)).",
  34. cause: error
  35. )
  36. }
  37. }
  38. }
  39. /// Deserializes a sequence of bytes into a Protobuf message.
  40. public struct ProtobufDeserializer<Message: SwiftProtobuf.Message>: GRPCCore.MessageDeserializer {
  41. public init() {}
  42. /// Deserializes a sequence of bytes into a `Message`.
  43. ///
  44. /// - Parameter serializedMessageBytes: The array of bytes to deserialize.
  45. /// - Returns: The deserialized message.
  46. @inlinable
  47. public func deserialize<Bytes: GRPCContiguousBytes>(
  48. _ serializedMessageBytes: Bytes
  49. ) throws -> Message {
  50. do {
  51. let message = try Message(serializedBytes: ContiguousBytesAdapter(serializedMessageBytes))
  52. return message
  53. } catch let error {
  54. throw RPCError(
  55. code: .invalidArgument,
  56. message: "Can't deserialize to message of type \(Message.self).",
  57. cause: error
  58. )
  59. }
  60. }
  61. }