LengthPrefixedMessageWriter.swift 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. public class LengthPrefixedMessageWriter {
  19. public static let metadataLength = 5
  20. private let compression: CompressionMechanism
  21. public init(compression: CompressionMechanism) {
  22. precondition(compression.supported, "compression mechanism \(compression) is not supported")
  23. self.compression = compression
  24. }
  25. /// Writes the data into a `ByteBuffer` as a gRPC length-prefixed message.
  26. ///
  27. /// - Parameters:
  28. /// - message: The serialized Protobuf message to write.
  29. /// - buffer: The buffer to write the message into.
  30. /// - Returns: A `ByteBuffer` containing a gRPC length-prefixed message.
  31. /// - Precondition: `compression.supported` is `true`.
  32. /// - Note: See `LengthPrefixedMessageReader` for more details on the format.
  33. func write(_ message: Data, into buffer: inout ByteBuffer) {
  34. buffer.reserveCapacity(LengthPrefixedMessageWriter.metadataLength + message.count)
  35. //! TODO: Add compression support, use the length and compressed content.
  36. buffer.writeInteger(Int8(compression.requiresFlag ? 1 : 0))
  37. buffer.writeInteger(UInt32(message.count))
  38. buffer.writeBytes(message)
  39. }
  40. }