ByteBuffer.swift 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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
  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. #if swift(>=5.0)
  36. self.underlyingByteBuffer = data.withUnsafeBytes { bytes in
  37. let buffer = bytes.bindMemory(to: UInt8.self).baseAddress
  38. return cgrpc_byte_buffer_create_by_copying_data(buffer, data.count)
  39. }
  40. #else
  41. self.underlyingByteBuffer = data.withUnsafeBytes { bytes in
  42. return cgrpc_byte_buffer_create_by_copying_data(bytes, data.count)
  43. }
  44. #endif
  45. }
  46. deinit {
  47. cgrpc_byte_buffer_destroy(underlyingByteBuffer)
  48. }
  49. /// Gets data from the contents of the ByteBuffer
  50. ///
  51. /// - Returns: data formed from the ByteBuffer contents
  52. public func data() -> Data? {
  53. var length: Int = 0
  54. guard let bytes = cgrpc_byte_buffer_copy_data(underlyingByteBuffer, &length) else {
  55. return nil
  56. }
  57. return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes),
  58. count: length,
  59. deallocator: .free)
  60. }
  61. }