FunctionsSerializer.swift 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. // Copyright 2022 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import Foundation
  15. private enum Constants {
  16. static let longType = "type.googleapis.com/google.protobuf.Int64Value"
  17. static let unsignedLongType = "type.googleapis.com/google.protobuf.UInt64Value"
  18. static let dateType = "type.googleapis.com/google.protobuf.Timestamp"
  19. }
  20. extension FunctionsSerializer {
  21. enum Error: Swift.Error {
  22. case unsupportedType(typeName: String)
  23. case unknownNumberType(charValue: String, number: NSNumber)
  24. case invalidValueForType(value: String, requestedType: String)
  25. }
  26. }
  27. final class FunctionsSerializer: Sendable {
  28. // MARK: - Internal APIs
  29. // This function only supports the following types and will otherwise throw
  30. // an error.
  31. // - NSNull (note: `nil` collection values from a Swift caller will be treated as NSNull)
  32. // - NSNumber
  33. // - NSString
  34. // - NSDicionary
  35. // - NSArray
  36. func encode(_ object: Any) throws -> Any {
  37. if object is NSNull {
  38. return object
  39. } else if object is NSNumber {
  40. return try encodeNumber(object as! NSNumber)
  41. } else if object is NSString {
  42. return object
  43. } else if let dict = object as? NSDictionary {
  44. let encoded = NSMutableDictionary()
  45. try dict.forEach { key, value in
  46. encoded[key] = try encode(value)
  47. }
  48. return encoded
  49. } else if let array = object as? NSArray {
  50. return try array.map { element in
  51. try encode(element)
  52. }
  53. } else {
  54. throw Error.unsupportedType(typeName: typeName(of: object))
  55. }
  56. }
  57. // This function only supports the following types and will otherwise throw
  58. // an error.
  59. // - NSNull (note: `nil` collection values from a Swift caller will be treated as NSNull)
  60. // - NSNumber
  61. // - NSString
  62. // - NSDicionary
  63. // - NSArray
  64. func decode(_ object: Any) throws -> Any {
  65. // Return these types as is. PORTING NOTE: Moved from the bottom of the func for readability.
  66. if let dict = object as? NSDictionary {
  67. if let requestedType = dict["@type"] as? String {
  68. guard let value = dict["value"] as? String else {
  69. // Seems like we should throw here - but this maintains compatibility.
  70. return dict
  71. }
  72. if let result = try decodeWrappedType(requestedType, value) {
  73. return result
  74. }
  75. // Treat unknown types as dictionaries, so we don't crash old clients when we add types.
  76. }
  77. let decoded = NSMutableDictionary()
  78. try dict.forEach { key, value in
  79. decoded[key] = try decode(value)
  80. }
  81. return decoded
  82. } else if let array = object as? NSArray {
  83. let decoded = NSMutableArray(capacity: array.count)
  84. try array.forEach { element in
  85. try decoded.add(decode(element) as Any)
  86. }
  87. return decoded
  88. } else if object is NSNumber || object is NSString || object is NSNull {
  89. return object as AnyObject
  90. }
  91. throw Error.unsupportedType(typeName: typeName(of: object))
  92. }
  93. // MARK: - Private Helpers
  94. private func typeName(of value: Any) -> String {
  95. String(describing: type(of: value))
  96. }
  97. private func encodeNumber(_ number: NSNumber) throws -> AnyObject {
  98. // Recover the underlying type of the number, using the method described here:
  99. // http://stackoverflow.com/questions/2518761/get-type-of-nsnumber
  100. let cType = number.objCType
  101. // Type Encoding values taken from
  102. // https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/
  103. // Articles/ocrtTypeEncodings.html
  104. switch cType[0] {
  105. case CChar("q".utf8.first!):
  106. // "long long" might be larger than JS supports, so make it a string.
  107. return ["@type": Constants.longType, "value": "\(number)"] as AnyObject
  108. case CChar("Q".utf8.first!):
  109. // "unsigned long long" might be larger than JS supports, so make it a string.
  110. return ["@type": Constants.unsignedLongType,
  111. "value": "\(number)"] as AnyObject
  112. case CChar("i".utf8.first!),
  113. CChar("s".utf8.first!),
  114. CChar("l".utf8.first!),
  115. CChar("I".utf8.first!),
  116. CChar("S".utf8.first!):
  117. // If it"s an integer that isn"t too long, so just use the number.
  118. return number
  119. case CChar("f".utf8.first!), CChar("d".utf8.first!):
  120. // It"s a float/double that"s not too large.
  121. return number
  122. case CChar("B".utf8.first!), CChar("c".utf8.first!), CChar("C".utf8.first!):
  123. // Boolean values are weird.
  124. //
  125. // On arm64, objCType of a BOOL-valued NSNumber will be "c", even though @encode(BOOL)
  126. // returns "B". "c" is the same as @encode(signed char). Unfortunately this means that
  127. // legitimate usage of signed chars is impossible, but this should be rare.
  128. //
  129. // Just return Boolean values as-is.
  130. return number
  131. default:
  132. // All documented codes should be handled above, so this shouldn"t happen.
  133. throw Error.unknownNumberType(charValue: String(cType[0]), number: number)
  134. }
  135. }
  136. private func decodeWrappedType(_ type: String, _ value: String) throws -> AnyObject? {
  137. switch type {
  138. case Constants.longType:
  139. let formatter = NumberFormatter()
  140. guard let n = formatter.number(from: value) else {
  141. throw Error.invalidValueForType(value: value, requestedType: type)
  142. }
  143. return n
  144. case Constants.unsignedLongType:
  145. // NSNumber formatter doesn't handle unsigned long long, so we have to parse it.
  146. let str = (value as NSString).utf8String
  147. var endPtr: UnsafeMutablePointer<CChar>?
  148. let returnValue = UInt64(strtoul(str, &endPtr, 10))
  149. guard String(returnValue) == value else {
  150. throw Error.invalidValueForType(value: value, requestedType: type)
  151. }
  152. return NSNumber(value: returnValue)
  153. default:
  154. return nil
  155. }
  156. }
  157. }