Coding.swift 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 Foundation
  17. import GRPCCore
  18. import SwiftProtobuf
  19. /// Serializes a Protobuf message into a sequence of bytes.
  20. public struct ProtobufSerializer<Message: SwiftProtobuf.Message>: GRPCCore.MessageSerializer {
  21. public init() {}
  22. /// Serializes a ``Message`` into a sequence of bytes.
  23. ///
  24. /// - Parameter message: The message to serialize.
  25. /// - Returns: An array of serialized bytes representing the message.
  26. public func serialize(_ message: Message) throws -> [UInt8] {
  27. do {
  28. let data = try message.serializedData()
  29. return Array(data)
  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. public func deserialize(_ serializedMessageBytes: [UInt8]) throws -> Message {
  47. do {
  48. let message = try Message(contiguousBytes: serializedMessageBytes)
  49. return message
  50. } catch let error {
  51. throw RPCError(
  52. code: .invalidArgument,
  53. message: "Can't deserialize to message of type \(Message.self)",
  54. cause: error
  55. )
  56. }
  57. }
  58. }