LengthPrefixedMessageWriter.swift 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. private let compression: CompressionAlgorithm?
  22. /// Whether the compression message flag should be set.
  23. private var shouldSetCompressionFlag: Bool {
  24. return self.compression != nil
  25. }
  26. init(compression: CompressionAlgorithm? = nil) {
  27. self.compression = compression
  28. }
  29. /// Writes the data into a `ByteBuffer` as a gRPC length-prefixed message.
  30. ///
  31. /// - Parameters:
  32. /// - message: The serialized Protobuf message to write.
  33. /// - buffer: The buffer to write the message into.
  34. /// - Returns: A `ByteBuffer` containing a gRPC length-prefixed message.
  35. /// - Precondition: `compression.supported` is `true`.
  36. /// - Note: See `LengthPrefixedMessageReader` for more details on the format.
  37. func write(_ message: Data, into buffer: inout ByteBuffer) {
  38. buffer.reserveCapacity(LengthPrefixedMessageWriter.metadataLength + message.count)
  39. //! TODO: Add compression support, use the length and compressed content.
  40. buffer.writeInteger(Int8(self.shouldSetCompressionFlag ? 1 : 0))
  41. buffer.writeInteger(UInt32(message.count))
  42. buffer.writeBytes(message)
  43. }
  44. }