Coding.swift 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. import GRPCCore
  17. 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. public func serialize(_ message: Message) throws -> [UInt8] {
  26. do {
  27. return try message.serializedBytes()
  28. } catch let error {
  29. throw RPCError(
  30. code: .invalidArgument,
  31. message: "Can't serialize message of type \(type(of: message)).",
  32. cause: error
  33. )
  34. }
  35. }
  36. }
  37. /// Deserializes a sequence of bytes into a Protobuf message.
  38. public struct ProtobufDeserializer<Message: SwiftProtobuf.Message>: GRPCCore.MessageDeserializer {
  39. public init() {}
  40. /// Deserializes a sequence of bytes into a ``Message``.
  41. ///
  42. /// - Parameter serializedMessageBytes: The array of bytes to deserialize.
  43. /// - Returns: The deserialized message.
  44. public func deserialize(_ serializedMessageBytes: [UInt8]) throws -> Message {
  45. do {
  46. let message = try Message(serializedBytes: serializedMessageBytes)
  47. return message
  48. } catch let error {
  49. throw RPCError(
  50. code: .invalidArgument,
  51. message: "Can't deserialize to message of type \(Message.self)",
  52. cause: error
  53. )
  54. }
  55. }
  56. }