LengthPrefixedMessageWriter.swift 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. /*
  2. * Copyright 2019, 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 NIO
  18. internal struct LengthPrefixedMessageWriter {
  19. static let metadataLength = 5
  20. /// The compression algorithm to use, if one should be used.
  21. let compression: CompressionAlgorithm?
  22. private let compressor: Zlib.Deflate?
  23. /// Whether the compression message flag should be set.
  24. private var shouldSetCompressionFlag: Bool {
  25. return self.compression != nil
  26. }
  27. init(compression: CompressionAlgorithm? = nil) {
  28. self.compression = compression
  29. switch self.compression?.algorithm {
  30. case .none, .some(.identity):
  31. self.compressor = nil
  32. case .some(.deflate):
  33. self.compressor = Zlib.Deflate(format: .deflate)
  34. case .some(.gzip):
  35. self.compressor = Zlib.Deflate(format: .gzip)
  36. }
  37. }
  38. /// Writes the data into a `ByteBuffer` as a gRPC length-prefixed message.
  39. ///
  40. /// - Parameters:
  41. /// - payload: The payload to serialize and write.
  42. /// - buffer: The buffer to write the message into.
  43. /// - Returns: A `ByteBuffer` containing a gRPC length-prefixed message.
  44. /// - Precondition: `compression.supported` is `true`.
  45. /// - Note: See `LengthPrefixedMessageReader` for more details on the format.
  46. func write(_ payload: GRPCPayload, into buffer: inout ByteBuffer, compressed: Bool = true) throws {
  47. buffer.reserveCapacity(buffer.writerIndex + LengthPrefixedMessageWriter.metadataLength)
  48. if compressed, let compressor = self.compressor {
  49. // Set the compression byte.
  50. buffer.writeInteger(UInt8(1))
  51. // Leave a gap for the length, we'll set it in a moment.
  52. let payloadSizeIndex = buffer.writerIndex
  53. buffer.moveWriterIndex(forwardBy: MemoryLayout<UInt32>.size)
  54. var messageBuf = ByteBufferAllocator().buffer(capacity: 0)
  55. try payload.serialize(into: &messageBuf)
  56. // Compress the message.
  57. let bytesWritten = try compressor.deflate(&messageBuf, into: &buffer)
  58. // Now fill in the message length.
  59. buffer.writePayloadLength(UInt32(bytesWritten), at: payloadSizeIndex)
  60. // Finally, the compression context should be reset between messages.
  61. compressor.reset()
  62. } else {
  63. // We could be using 'identity' compression, but since the result is the same we'll just
  64. // say it isn't compressed.
  65. buffer.writeInteger(UInt8(0))
  66. // Leave a gap for the length, we'll set it in a moment.
  67. let payloadSizeIndex = buffer.writerIndex
  68. buffer.moveWriterIndex(forwardBy: MemoryLayout<UInt32>.size)
  69. let payloadPrefixedBytes = buffer.readableBytes
  70. // Writes the payload into the buffer
  71. try payload.serialize(into: &buffer)
  72. // Calculates the Written bytes with respect to the prefixed ones
  73. let bytesWritten = buffer.readableBytes - payloadPrefixedBytes
  74. // Write the message length.
  75. buffer.writePayloadLength(UInt32(bytesWritten), at: payloadSizeIndex)
  76. }
  77. }
  78. }
  79. extension ByteBuffer {
  80. @discardableResult
  81. mutating func writePayloadLength(_ length: UInt32, at index: Int) -> Int {
  82. let writerIndex = self.writerIndex
  83. defer {
  84. self.moveWriterIndex(to: writerIndex)
  85. }
  86. self.moveWriterIndex(to: index)
  87. return self.writeInteger(length)
  88. }
  89. }