Serialization.swift 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /*
  2. * Copyright 2020, 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 NIO
  17. import NIOFoundationCompat
  18. import SwiftProtobuf
  19. internal protocol MessageSerializer {
  20. associatedtype Input
  21. /// Serializes `input` into a `ByteBuffer` allocated using the provided `allocator`.
  22. ///
  23. /// - Parameters:
  24. /// - input: The element to serialize.
  25. /// - allocator: A `ByteBufferAllocator`.
  26. func serialize(_ input: Input, allocator: ByteBufferAllocator) throws -> ByteBuffer
  27. }
  28. internal protocol MessageDeserializer {
  29. associatedtype Output
  30. /// Deserializes `byteBuffer` to produce a single `Output`.
  31. ///
  32. /// - Parameter byteBuffer: The `ByteBuffer` to deserialize.
  33. func deserialize(byteBuffer: ByteBuffer) throws -> Output
  34. }
  35. // MARK: Protobuf
  36. internal struct ProtobufSerializer<Message: SwiftProtobuf.Message>: MessageSerializer {
  37. internal func serialize(_ message: Message, allocator: ByteBufferAllocator) throws -> ByteBuffer {
  38. // Serialize the message.
  39. let serialized = try message.serializedData()
  40. // Allocate enough space and an extra 5 leading bytes. This a minor optimisation win: the length
  41. // prefixed message writer can re-use the leading 5 bytes without needing to allocate a new
  42. // buffer and copy over the serialized message.
  43. var buffer = allocator.buffer(capacity: serialized.count + 5)
  44. buffer.writeBytes(Array(repeating: 0, count: 5))
  45. buffer.moveReaderIndex(forwardBy: 5)
  46. // Now write the serialized message.
  47. buffer.writeBytes(serialized)
  48. return buffer
  49. }
  50. }
  51. internal struct ProtobufDeserializer<Message: SwiftProtobuf.Message>: MessageDeserializer {
  52. internal func deserialize(byteBuffer: ByteBuffer) throws -> Message {
  53. var buffer = byteBuffer
  54. // '!' is okay; we can always read 'readableBytes'.
  55. let data = buffer.readData(length: buffer.readableBytes)!
  56. return try Message(serializedData: data)
  57. }
  58. }
  59. // MARK: GRPCPayload
  60. internal struct GRPCPayloadSerializer<Message: GRPCPayload>: MessageSerializer {
  61. internal func serialize(_ message: Message, allocator: ByteBufferAllocator) throws -> ByteBuffer {
  62. // Reserve 5 leading bytes. This a minor optimisation win: the length prefixed message writer
  63. // can re-use the leading 5 bytes without needing to allocate a new buffer and copy over the
  64. // serialized message.
  65. var buffer = allocator.buffer(repeating: 0, count: 5)
  66. let readerIndex = buffer.readerIndex
  67. let writerIndex = buffer.writerIndex
  68. // Serialize the payload into the buffer.
  69. try message.serialize(into: &buffer)
  70. // Ensure 'serialize(into:)' didn't do anything strange.
  71. assert(buffer.readerIndex == readerIndex, "serialize(into:) must not move the readerIndex")
  72. assert(buffer.writerIndex >= writerIndex, "serialize(into:) must not move the writerIndex backwards")
  73. assert(buffer.getBytes(at: readerIndex, length: 5) == Array(repeating: 0, count: 5),
  74. "serialize(into:) must not write over existing written bytes")
  75. // 'read' the first 5 bytes so that the buffer's readable bytes are only the bytes of the
  76. // serialized message.
  77. buffer.moveReaderIndex(forwardBy: 5)
  78. return buffer
  79. }
  80. }
  81. internal struct GRPCPayloadDeserializer<Message: GRPCPayload>: MessageDeserializer {
  82. internal func deserialize(byteBuffer: ByteBuffer) throws -> Message {
  83. var buffer = byteBuffer
  84. return try Message(serializedByteBuffer: &buffer)
  85. }
  86. }