ByteBuffer.swift 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. * Copyright 2016, 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. #if SWIFT_PACKAGE
  17. import CgRPC
  18. #endif
  19. import Foundation // for String.Encoding
  20. /// Representation of raw data that may be sent and received using gRPC
  21. public class ByteBuffer {
  22. /// Pointer to underlying C representation
  23. let underlyingByteBuffer: UnsafeMutableRawPointer
  24. /// Creates a ByteBuffer from an underlying C representation.
  25. /// The ByteBuffer takes ownership of the passed-in representation.
  26. ///
  27. /// - Parameter underlyingByteBuffer: the underlying C representation
  28. init(underlyingByteBuffer: UnsafeMutableRawPointer) {
  29. self.underlyingByteBuffer = underlyingByteBuffer
  30. }
  31. /// Creates a byte buffer that contains a copy of the contents of `data`
  32. ///
  33. /// - Parameter data: the data to store in the buffer
  34. public init(data: Data) {
  35. var underlyingByteBuffer: UnsafeMutableRawPointer?
  36. data.withUnsafeBytes { bytes in
  37. underlyingByteBuffer = cgrpc_byte_buffer_create_by_copying_data(bytes, data.count)
  38. }
  39. self.underlyingByteBuffer = underlyingByteBuffer!
  40. }
  41. deinit {
  42. cgrpc_byte_buffer_destroy(underlyingByteBuffer)
  43. }
  44. /// Gets data from the contents of the ByteBuffer
  45. ///
  46. /// - Returns: data formed from the ByteBuffer contents
  47. public func data() -> Data? {
  48. var length: Int = 0
  49. guard let bytes = cgrpc_byte_buffer_copy_data(underlyingByteBuffer, &length) else {
  50. return nil
  51. }
  52. return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes),
  53. count: length,
  54. deallocator: .free)
  55. }
  56. }