ByteBuffer.swift 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. internal var 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. internal 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. data.withUnsafeBytes { (bytes) in
  36. underlyingByteBuffer = cgrpc_byte_buffer_create_by_copying_data(bytes, data.count)
  37. }
  38. }
  39. deinit {
  40. cgrpc_byte_buffer_destroy(underlyingByteBuffer);
  41. }
  42. /// Gets data from the contents of the ByteBuffer
  43. ///
  44. /// - Returns: data formed from the ByteBuffer contents
  45. public func data() -> Data? {
  46. var length : Int = 0
  47. guard let bytes = cgrpc_byte_buffer_copy_data(underlyingByteBuffer, &length) else {
  48. return nil
  49. }
  50. return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes),
  51. count: length,
  52. deallocator: .free)
  53. }
  54. }