FunctionsSerializer.swift 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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. enum SerializerError: Error {
  21. // TODO: Add parameters class name and value
  22. case unsupportedType // (className: String, value: AnyObject)
  23. case unknownNumberType(charValue: String, number: NSNumber)
  24. case invalidValueForType(value: String, requestedType: String)
  25. }
  26. class FUNSerializer: NSObject {
  27. private let dateFormatter: DateFormatter
  28. override init() {
  29. dateFormatter = DateFormatter()
  30. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
  31. dateFormatter.timeZone = TimeZone(identifier: "UTC")
  32. }
  33. // MARK: - Internal APIs
  34. internal func encode(_ object: Any) throws -> AnyObject {
  35. if object is NSNull {
  36. return object as AnyObject
  37. } else if object is NSNumber {
  38. return try encodeNumber(object as! NSNumber)
  39. } else if object is NSString {
  40. return object as AnyObject
  41. } else if object is NSDictionary {
  42. let dict = object as! NSDictionary
  43. let encoded: NSMutableDictionary = .init()
  44. dict.enumerateKeysAndObjects { key, obj, _ in
  45. // TODO(wilsonryan): Not exact translation
  46. let anyObj = obj as AnyObject
  47. let stringKey = key as! String
  48. let value = try! encode(anyObj)
  49. encoded[stringKey] = value
  50. }
  51. return encoded
  52. } else if object is NSArray {
  53. let array = object as! NSArray
  54. let encoded = NSMutableArray()
  55. for item in array {
  56. let anyItem = item as AnyObject
  57. let encodedItem = try encode(anyItem)
  58. encoded.add(encodedItem)
  59. }
  60. return encoded
  61. } else {
  62. throw SerializerError.unsupportedType
  63. }
  64. }
  65. internal func decode(_ object: Any) throws -> AnyObject? {
  66. // Return these types as is. PORTING NOTE: Moved from the bottom of the func for readability.
  67. if let dict = object as? NSDictionary {
  68. if let requestedType = dict["@type"] as? String {
  69. guard let value = dict["value"] as? String else {
  70. // Seems like we should throw here - but this maintains compatiblity.
  71. return dict
  72. }
  73. let result = try decodeWrappedType(requestedType, value)
  74. if result != nil { return result }
  75. // Treat unknown types as dictionaries, so we don't crash old clients when we add types.
  76. }
  77. let decoded = NSMutableDictionary()
  78. var decodeError: Error?
  79. dict.enumerateKeysAndObjects { key, obj, stopPointer in
  80. do {
  81. let decodedItem = try self.decode(obj)
  82. decoded[key] = decodedItem
  83. } catch {
  84. decodeError = error
  85. stopPointer.pointee = true
  86. return
  87. }
  88. }
  89. // Throw the internal error that popped up, if it did.
  90. if let decodeError = decodeError {
  91. throw decodeError
  92. }
  93. return decoded
  94. } else if let array = object as? NSArray {
  95. let result = NSMutableArray(capacity: array.count)
  96. for obj in array {
  97. // TODO: Is this data loss? The API is a bit weird.
  98. if let decoded = try decode(obj) {
  99. result.add(decoded)
  100. }
  101. }
  102. return result
  103. } else if object is NSNumber || object is NSString || object is NSNull {
  104. return object as AnyObject
  105. }
  106. throw SerializerError.unsupportedType
  107. }
  108. // MARK: - Private Helpers
  109. private func encodeNumber(_ number: NSNumber) throws -> AnyObject {
  110. // Recover the underlying type of the number, using the method described here:
  111. // http://stackoverflow.com/questions/2518761/get-type-of-nsnumber
  112. let cType = number.objCType
  113. // Type Encoding values taken from
  114. // https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/
  115. // Articles/ocrtTypeEncodings.html
  116. switch cType[0] {
  117. case CChar("q".utf8.first!):
  118. // "long long" might be larger than JS supports, so make it a string.
  119. return ["@type": Constants.longType, "value": "\(number)"] as AnyObject
  120. case CChar("Q".utf8.first!):
  121. // "unsigned long long" might be larger than JS supports, so make it a string.
  122. return ["@type": Constants.unsignedLongType,
  123. "value": "\(number)"] as AnyObject
  124. case CChar("i".utf8.first!),
  125. CChar("s".utf8.first!),
  126. CChar("l".utf8.first!),
  127. CChar("I".utf8.first!),
  128. CChar("S".utf8.first!):
  129. // If it"s an integer that isn"t too long, so just use the number.
  130. return number
  131. case CChar("f".utf8.first!), CChar("d".utf8.first!):
  132. // It"s a float/double that"s not too large.
  133. return number
  134. case CChar("B".utf8.first!), CChar("c".utf8.first!), CChar("C".utf8.first!):
  135. // Boolean values are weird.
  136. //
  137. // On arm64, objCType of a BOOL-valued NSNumber will be "c", even though @encode(BOOL)
  138. // returns "B". "c" is the same as @encode(signed char). Unfortunately this means that
  139. // legitimate usage of signed chars is impossible, but this should be rare.
  140. //
  141. // Just return Boolean values as-is.
  142. return number
  143. default:
  144. // All documented codes should be handled above, so this shouldn"t happen.
  145. throw SerializerError.unknownNumberType(charValue: String(cType[0]), number: number)
  146. }
  147. }
  148. private func decodeWrappedType(_ type: String, _ value: String) throws -> AnyObject? {
  149. switch type {
  150. case Constants.longType:
  151. let formatter = NumberFormatter()
  152. guard let n = formatter.number(from: value) else {
  153. throw SerializerError.invalidValueForType(value: value, requestedType: type)
  154. }
  155. return n
  156. case Constants.unsignedLongType:
  157. // NSNumber formatter doesn't handle unsigned long long, so we have to parse it.
  158. let str = (value as NSString).utf8String
  159. var endPtr: UnsafeMutablePointer<CChar>?
  160. let returnValue = UInt64(strtoul(str, &endPtr, 10))
  161. guard String(returnValue) == value else {
  162. throw SerializerError.invalidValueForType(value: value, requestedType: type)
  163. }
  164. return NSNumber(value: returnValue)
  165. default:
  166. return nil
  167. }
  168. }
  169. }