FunctionsSerializer.swift 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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 paramters class name and value
  22. case unsupportedType // (className: String, value: AnyObject)
  23. case unknownNumberType(charValue: String, number: NSNumber)
  24. case unimplemented // TODO(wilsonryan): REMOVE
  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: - Public 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 dict["@type"] != nil {
  69. var result: AnyObject?
  70. do {
  71. result = try decodeWrappedType(dict)
  72. } catch {
  73. return nil
  74. }
  75. if result != nil { return result }
  76. // Treat unknown types as dictionaries, so we don't crash old clients when we add types.
  77. }
  78. let decoded = NSMutableDictionary()
  79. var decodeError: Error?
  80. dict.enumerateKeysAndObjects { key, obj, stopPointer in
  81. do {
  82. let decodedItem = try self.decode(obj)
  83. decoded[key] = decodedItem
  84. } catch {
  85. decodeError = error
  86. stopPointer.pointee = true
  87. return
  88. }
  89. }
  90. // Throw the internal error that popped up, if it did.
  91. if let decodeError = decodeError {
  92. throw decodeError
  93. }
  94. return decoded
  95. } else if let array = object as? NSArray {
  96. let result = NSMutableArray(capacity: array.count)
  97. for obj in array {
  98. // TODO: Is this data loss? The API is a bit weird.
  99. if let decoded = try decode(obj) {
  100. result.add(decoded)
  101. }
  102. }
  103. return result
  104. } else if object is NSNumber || object is NSString || object is NSNull {
  105. return object as AnyObject
  106. }
  107. throw SerializerError.unsupportedType
  108. }
  109. // MARK: - Private Helpers
  110. private func encodeNumber(_ number: NSNumber) throws -> AnyObject {
  111. // Recover the underlying type of the number, using the method described here:
  112. // http://stackoverflow.com/questions/2518761/get-type-of-nsnumber
  113. let cType = number.objCType
  114. // TODO: Use `CFNumberGetType(number)` instead and use that enum, although `unsigned long long`
  115. // is missing.
  116. // let numberType = CFNumberGetType(number)
  117. // Type Encoding values taken from
  118. // https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/
  119. // Articles/ocrtTypeEncodings.html
  120. switch cType[0] {
  121. case CChar("q".utf8.first!):
  122. // "long long" might be larger than JS supports, so make it a string.
  123. return ["@type": Constants.longType, "value": "\(number)"] as AnyObject
  124. case CChar("Q".utf8.first!):
  125. // "unsigned long long" might be larger than JS supports, so make it a string.
  126. return ["@type": Constants.unsignedLongType,
  127. "value": "\(number)"] as AnyObject
  128. case CChar("i".utf8.first!),
  129. CChar("s".utf8.first!),
  130. CChar("l".utf8.first!),
  131. CChar("I".utf8.first!),
  132. CChar("S".utf8.first!):
  133. // If it"s an integer that isn"t too long, so just use the number.
  134. return number
  135. case CChar("f".utf8.first!), CChar("d".utf8.first!):
  136. // It"s a float/double that"s not too large.
  137. return number
  138. case CChar("B".utf8.first!), CChar("c".utf8.first!), CChar("C".utf8.first!):
  139. // Boolean values are weird.
  140. //
  141. // On arm64, objCType of a BOOL-valued NSNumber will be "c", even though @encode(BOOL)
  142. // returns "B". "c" is the same as @encode(signed char). Unfortunately this means that
  143. // legitimate usage of signed chars is impossible, but this should be rare.
  144. //
  145. // Just return Boolean values as-is.
  146. return number
  147. default:
  148. // All documented codes should be handled above, so this shouldn"t happen.
  149. throw SerializerError.unknownNumberType(charValue: String(cType[0]), number: number)
  150. }
  151. }
  152. private func decodeWrappedType(_ wrapped: NSDictionary) throws -> AnyObject? {
  153. let type = wrapped["@type"] as! String
  154. guard let value = wrapped["value"] as? String else {
  155. return nil
  156. }
  157. switch type {
  158. case Constants.longType:
  159. let formatter = NumberFormatter()
  160. guard let n = formatter.number(from: value) else {
  161. // TODO: Throw FUNInvalidNumberError(value, wrapped);
  162. return nil
  163. }
  164. return n
  165. case Constants.unsignedLongType:
  166. // NSNumber formatter doesn't handle unsigned long long, so we have to parse it.
  167. let str = value.utf8
  168. // TODO: Port this atrocity
  169. throw SerializerError.unimplemented
  170. /*
  171. const char *str = value.UTF8String;
  172. char *end = NULL;
  173. unsigned long long n = strtoull(str, &end, 10);
  174. if (errno == ERANGE) {
  175. // This number was actually too big for an unsigned long long.
  176. if (error != NULL) {
  177. *error = FUNInvalidNumberError(value, wrapped);
  178. }
  179. return nil;
  180. }
  181. if (*end) {
  182. // The whole string wasn't parsed.
  183. if (error != NULL) {
  184. *error = FUNInvalidNumberError(value, wrapped);
  185. }
  186. return nil;
  187. }
  188. return @(n);
  189. */
  190. default:
  191. return nil
  192. }
  193. }
  194. }