Metadata.swift 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  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. /// Metadata sent with gRPC messages
  21. public class Metadata {
  22. public enum Error: Swift.Error {
  23. /// Field ownership can only be transferred once. Likewise, it is not advisable to write to a metadata array whose
  24. /// fields we do not own.
  25. case doesNotOwnFields
  26. }
  27. /// Pointer to underlying C representation
  28. fileprivate let underlyingArray: UnsafeMutableRawPointer
  29. /// Ownership of the fields inside metadata arrays provided by `grpc_op_recv_initial_metadata` and
  30. /// `grpc_op_recv_status_on_client` is retained by the gRPC library. Similarly, passing metadata to gRPC for sending
  31. /// to the client for sending/receiving also transfers ownership. However, before we have passed that metadata to
  32. /// gRPC, we are still responsible for releasing its fields. This variable tracks that.
  33. fileprivate var ownsFields: Bool
  34. init(underlyingArray: UnsafeMutableRawPointer, ownsFields: Bool) {
  35. self.underlyingArray = underlyingArray
  36. self.ownsFields = ownsFields
  37. }
  38. public init() {
  39. underlyingArray = cgrpc_metadata_array_create()
  40. ownsFields = true
  41. }
  42. public init(_ pairs: [String: String]) throws {
  43. underlyingArray = cgrpc_metadata_array_create()
  44. ownsFields = true
  45. for (key, value) in pairs {
  46. try add(key: key, value: value)
  47. }
  48. }
  49. deinit {
  50. if ownsFields {
  51. cgrpc_metadata_array_unref_fields(underlyingArray)
  52. }
  53. cgrpc_metadata_array_destroy(underlyingArray)
  54. }
  55. public func count() -> Int {
  56. return cgrpc_metadata_array_get_count(underlyingArray)
  57. }
  58. // Returns `nil` for non-UTF8 metadata key strings.
  59. public func key(_ index: Int) -> String? {
  60. // We actually know that this method will never return nil,
  61. // so we can forcibly unwrap the result. (Also below.)
  62. let keyData = cgrpc_metadata_array_copy_key_at_index(underlyingArray, index)!
  63. defer { cgrpc_free_copied_string(keyData) }
  64. return String(cString: keyData, encoding: String.Encoding.utf8)
  65. }
  66. // Returns `nil` for non-UTF8 metadata value strings.
  67. public func value(_ index: Int) -> String? {
  68. // We actually know that this method will never return nil,
  69. // so we can forcibly unwrap the result. (Also below.)
  70. let valueData = cgrpc_metadata_array_copy_value_at_index(underlyingArray, index)!
  71. defer { cgrpc_free_copied_string(valueData) }
  72. return String(cString: valueData, encoding: String.Encoding.utf8)
  73. }
  74. public func add(key: String, value: String) throws {
  75. if !ownsFields {
  76. throw Error.doesNotOwnFields
  77. }
  78. cgrpc_metadata_array_append_metadata(underlyingArray, key, value)
  79. }
  80. public var dictionaryRepresentation: [String: String] {
  81. var result: [String: String] = [:]
  82. var unknownKeyCount = 0
  83. for i in 0..<count() {
  84. let key: String
  85. if let unwrappedKey = self.key(i) {
  86. key = unwrappedKey
  87. } else {
  88. key = "(unknown\(unknownKeyCount))"
  89. unknownKeyCount += 1
  90. }
  91. result[key] = self.value(i) ?? "(unknown)"
  92. }
  93. return result
  94. }
  95. public func copy() -> Metadata {
  96. return Metadata(underlyingArray: cgrpc_metadata_array_copy(underlyingArray), ownsFields: true)
  97. }
  98. func getUnderlyingArrayAndTransferFieldOwnership() throws -> UnsafeMutableRawPointer {
  99. if !ownsFields {
  100. throw Error.doesNotOwnFields
  101. }
  102. ownsFields = false
  103. return underlyingArray
  104. }
  105. }
  106. extension Metadata {
  107. public subscript(_ key: String) -> String? {
  108. for i in 0..<self.count() {
  109. let currentKey = self.key(i)
  110. guard currentKey == key
  111. else { continue }
  112. return self.value(i)
  113. }
  114. return nil
  115. }
  116. public func data(forKey key: String) -> Data? {
  117. for index in 0..<count() {
  118. guard self.key(index) == key else { continue }
  119. let byteBuffer = ByteBuffer(underlyingByteBuffer: cgrpc_metadata_array_copy_data_value_at_index(underlyingArray, index))
  120. return byteBuffer.data()
  121. }
  122. return nil
  123. }
  124. }