FirebaseDataEncoder.swift 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585
  1. // This file is derived from swift/stdlib/public/Darwin/Foundation/JSONEncoder.swift
  2. //===----------------------------------------------------------------------===//
  3. //
  4. // This source file is part of the Swift.org open source project
  5. //
  6. // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
  7. // Licensed under Apache License v2.0 with Runtime Library Exception
  8. //
  9. // See https://swift.org/LICENSE.txt for license information
  10. // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
  11. //
  12. //===----------------------------------------------------------------------===//
  13. import Foundation
  14. extension DecodingError {
  15. /// Returns a `.typeMismatch` error describing the expected type.
  16. ///
  17. /// - parameter path: The path of `CodingKey`s taken to decode a value of this type.
  18. /// - parameter expectation: The type expected to be encountered.
  19. /// - parameter reality: The value that was encountered instead of the expected type.
  20. /// - returns: A `DecodingError` with the appropriate path and debug description.
  21. internal static func _typeMismatch(at path: [CodingKey], expectation: Any.Type, reality: Any) -> DecodingError {
  22. let description = "Expected to decode \(expectation) but found \(_typeDescription(of: reality)) instead."
  23. return .typeMismatch(expectation, Context(codingPath: path, debugDescription: description))
  24. }
  25. /// Returns a description of the type of `value` appropriate for an error message.
  26. ///
  27. /// - parameter value: The value whose type to describe.
  28. /// - returns: A string describing `value`.
  29. /// - precondition: `value` is one of the types below.
  30. fileprivate static func _typeDescription(of value: Any) -> String {
  31. if value is NSNull {
  32. return "a null value"
  33. } else if value is NSNumber /* FIXME: If swift-corelibs-foundation isn't updated to use NSNumber, this check will be necessary: || value is Int || value is Double */ {
  34. return "a number"
  35. } else if value is String {
  36. return "a string/data"
  37. } else if value is [Any] {
  38. return "an array"
  39. } else if value is [String : Any] {
  40. return "a dictionary"
  41. } else {
  42. return "\(type(of: value))"
  43. }
  44. }
  45. }
  46. /// A marker protocol used to determine whether a value is a `String`-keyed `Dictionary`
  47. /// containing `Encodable` values (in which case it should be exempt from key conversion strategies).
  48. ///
  49. /// NOTE: The architecture and environment check is due to a bug in the current (2018-08-08) Swift 4.2
  50. /// runtime when running on i386 simulator. The issue is tracked in https://bugs.swift.org/browse/SR-8276
  51. /// Making the protocol `internal` instead of `fileprivate` works around this issue.
  52. /// Once SR-8276 is fixed, this check can be removed and the protocol always be made fileprivate.
  53. #if arch(i386) || arch(arm)
  54. internal protocol _JSONStringDictionaryEncodableMarker { }
  55. #else
  56. fileprivate protocol _JSONStringDictionaryEncodableMarker { }
  57. #endif
  58. extension Dictionary : _JSONStringDictionaryEncodableMarker where Key == String, Value: Encodable { }
  59. /// A marker protocol used to determine whether a value is a `String`-keyed `Dictionary`
  60. /// containing `Decodable` values (in which case it should be exempt from key conversion strategies).
  61. ///
  62. /// The marker protocol also provides access to the type of the `Decodable` values,
  63. /// which is needed for the implementation of the key conversion strategy exemption.
  64. ///
  65. /// NOTE: Please see comment above regarding SR-8276
  66. #if arch(i386) || arch(arm)
  67. internal protocol _JSONStringDictionaryDecodableMarker {
  68. static var elementType: Decodable.Type { get }
  69. }
  70. #else
  71. fileprivate protocol _JSONStringDictionaryDecodableMarker {
  72. static var elementType: Decodable.Type { get }
  73. }
  74. #endif
  75. extension Dictionary : _JSONStringDictionaryDecodableMarker where Key == String, Value: Decodable {
  76. static var elementType: Decodable.Type { return Value.self }
  77. }
  78. //===----------------------------------------------------------------------===//
  79. // JSON Encoder
  80. //===----------------------------------------------------------------------===//
  81. /// `JSONEncoder` facilitates the encoding of `Encodable` values into JSON.
  82. // NOTE: older overlays had Foundation.JSONEncoder as the ObjC name.
  83. // The two must coexist, so it was renamed. The old name must not be
  84. // used in the new runtime. _TtC10Foundation13__JSONEncoder is the
  85. // mangled name for Foundation.__JSONEncoder.
  86. public class FirebaseDataEncoder {
  87. // MARK: Options
  88. /// The strategy to use for encoding `Date` values.
  89. public enum DateEncodingStrategy {
  90. /// Defer to `Date` for choosing an encoding. This is the default strategy.
  91. case deferredToDate
  92. /// Encode the `Date` as a UNIX timestamp (as a JSON number).
  93. case secondsSince1970
  94. /// Encode the `Date` as UNIX millisecond timestamp (as a JSON number).
  95. case millisecondsSince1970
  96. /// Encode the `Date` as an ISO-8601-formatted string (in RFC 3339 format).
  97. @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
  98. case iso8601
  99. /// Encode the `Date` as a string formatted by the given formatter.
  100. case formatted(DateFormatter)
  101. /// Encode the `Date` as a custom value encoded by the given closure.
  102. ///
  103. /// If the closure fails to encode a value into the given encoder, the encoder will encode an empty automatic container in its place.
  104. case custom((Date, Swift.Encoder) throws -> Void)
  105. }
  106. /// The strategy to use for encoding `Data` values.
  107. public enum DataEncodingStrategy {
  108. /// Defer to `Data` for choosing an encoding.
  109. case deferredToData
  110. /// Encoded the `Data` as a Base64-encoded string. This is the default strategy.
  111. case base64
  112. /// Encode the `Data` as a custom value encoded by the given closure.
  113. ///
  114. /// If the closure fails to encode a value into the given encoder, the encoder will encode an empty automatic container in its place.
  115. case custom((Data, Swift.Encoder) throws -> Void)
  116. }
  117. /// The strategy to use for non-JSON-conforming floating-point values (IEEE 754 infinity and NaN).
  118. public enum NonConformingFloatEncodingStrategy {
  119. /// Throw upon encountering non-conforming values. This is the default strategy.
  120. case `throw`
  121. /// Encode the values using the given representation strings.
  122. case convertToString(positiveInfinity: String, negativeInfinity: String, nan: String)
  123. }
  124. /// The strategy to use for automatically changing the value of keys before encoding.
  125. public enum KeyEncodingStrategy {
  126. /// Use the keys specified by each type. This is the default strategy.
  127. case useDefaultKeys
  128. /// Convert from "camelCaseKeys" to "snake_case_keys" before writing a key to JSON payload.
  129. ///
  130. /// Capital characters are determined by testing membership in `CharacterSet.uppercaseLetters` and `CharacterSet.lowercaseLetters` (Unicode General Categories Lu and Lt).
  131. /// The conversion to lower case uses `Locale.system`, also known as the ICU "root" locale. This means the result is consistent regardless of the current user's locale and language preferences.
  132. ///
  133. /// Converting from camel case to snake case:
  134. /// 1. Splits words at the boundary of lower-case to upper-case
  135. /// 2. Inserts `_` between words
  136. /// 3. Lowercases the entire string
  137. /// 4. Preserves starting and ending `_`.
  138. ///
  139. /// For example, `oneTwoThree` becomes `one_two_three`. `_oneTwoThree_` becomes `_one_two_three_`.
  140. ///
  141. /// - Note: Using a key encoding strategy has a nominal performance cost, as each string key has to be converted.
  142. case convertToSnakeCase
  143. /// Provide a custom conversion to the key in the encoded JSON from the keys specified by the encoded types.
  144. /// The full path to the current encoding position is provided for context (in case you need to locate this key within the payload). The returned key is used in place of the last component in the coding path before encoding.
  145. /// If the result of the conversion is a duplicate key, then only one value will be present in the result.
  146. case custom((_ codingPath: [CodingKey]) -> CodingKey)
  147. fileprivate static func _convertToSnakeCase(_ stringKey: String) -> String {
  148. guard !stringKey.isEmpty else { return stringKey }
  149. var words : [Range<String.Index>] = []
  150. // The general idea of this algorithm is to split words on transition from lower to upper case, then on transition of >1 upper case characters to lowercase
  151. //
  152. // myProperty -> my_property
  153. // myURLProperty -> my_url_property
  154. //
  155. // We assume, per Swift naming conventions, that the first character of the key is lowercase.
  156. var wordStart = stringKey.startIndex
  157. var searchRange = stringKey.index(after: wordStart)..<stringKey.endIndex
  158. // Find next uppercase character
  159. while let upperCaseRange = stringKey.rangeOfCharacter(from: CharacterSet.uppercaseLetters, options: [], range: searchRange) {
  160. let untilUpperCase = wordStart..<upperCaseRange.lowerBound
  161. words.append(untilUpperCase)
  162. // Find next lowercase character
  163. searchRange = upperCaseRange.lowerBound..<searchRange.upperBound
  164. guard let lowerCaseRange = stringKey.rangeOfCharacter(from: CharacterSet.lowercaseLetters, options: [], range: searchRange) else {
  165. // There are no more lower case letters. Just end here.
  166. wordStart = searchRange.lowerBound
  167. break
  168. }
  169. // Is the next lowercase letter more than 1 after the uppercase? If so, we encountered a group of uppercase letters that we should treat as its own word
  170. let nextCharacterAfterCapital = stringKey.index(after: upperCaseRange.lowerBound)
  171. if lowerCaseRange.lowerBound == nextCharacterAfterCapital {
  172. // The next character after capital is a lower case character and therefore not a word boundary.
  173. // Continue searching for the next upper case for the boundary.
  174. wordStart = upperCaseRange.lowerBound
  175. } else {
  176. // There was a range of >1 capital letters. Turn those into a word, stopping at the capital before the lower case character.
  177. let beforeLowerIndex = stringKey.index(before: lowerCaseRange.lowerBound)
  178. words.append(upperCaseRange.lowerBound..<beforeLowerIndex)
  179. // Next word starts at the capital before the lowercase we just found
  180. wordStart = beforeLowerIndex
  181. }
  182. searchRange = lowerCaseRange.upperBound..<searchRange.upperBound
  183. }
  184. words.append(wordStart..<searchRange.upperBound)
  185. let result = words.map({ (range) in
  186. return stringKey[range].lowercased()
  187. }).joined(separator: "_")
  188. return result
  189. }
  190. }
  191. /// The strategy to use in encoding dates. Defaults to `.deferredToDate`.
  192. open var dateEncodingStrategy: DateEncodingStrategy = .deferredToDate
  193. /// The strategy to use in encoding binary data. Defaults to `.base64`.
  194. open var dataEncodingStrategy: DataEncodingStrategy = .base64
  195. /// The strategy to use in encoding non-conforming numbers. Defaults to `.throw`.
  196. open var nonConformingFloatEncodingStrategy: NonConformingFloatEncodingStrategy = .throw
  197. /// The strategy to use for encoding keys. Defaults to `.useDefaultKeys`.
  198. open var keyEncodingStrategy: KeyEncodingStrategy = .useDefaultKeys
  199. /// Contextual user-provided information for use during encoding.
  200. open var userInfo: [CodingUserInfoKey : Any] = [:]
  201. /// Options set on the top-level encoder to pass down the encoding hierarchy.
  202. fileprivate struct _Options {
  203. let dateEncodingStrategy: DateEncodingStrategy
  204. let dataEncodingStrategy: DataEncodingStrategy
  205. let nonConformingFloatEncodingStrategy: NonConformingFloatEncodingStrategy
  206. let keyEncodingStrategy: KeyEncodingStrategy
  207. let userInfo: [CodingUserInfoKey : Any]
  208. }
  209. /// The options set on the top-level encoder.
  210. fileprivate var options: _Options {
  211. return _Options(dateEncodingStrategy: dateEncodingStrategy,
  212. dataEncodingStrategy: dataEncodingStrategy,
  213. nonConformingFloatEncodingStrategy: nonConformingFloatEncodingStrategy,
  214. keyEncodingStrategy: keyEncodingStrategy,
  215. userInfo: userInfo)
  216. }
  217. // MARK: - Constructing a JSON Encoder
  218. /// Initializes `self` with default strategies.
  219. public init() {}
  220. // MARK: - Encoding Values
  221. /// Encodes the given top-level value and returns its JSON representation.
  222. ///
  223. /// - parameter value: The value to encode.
  224. /// - returns: A new `Data` value containing the encoded JSON data.
  225. /// - throws: `EncodingError.invalidValue` if a non-conforming floating-point value is encountered during encoding, and the encoding strategy is `.throw`.
  226. /// - throws: An error if any value throws an error during encoding.
  227. open func encode<T : Encodable>(_ value: T) throws -> Any {
  228. let encoder = __JSONEncoder(options: self.options)
  229. guard let topLevel = try encoder.box_(value) else {
  230. throw Swift.EncodingError.invalidValue(value,
  231. Swift.EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) did not encode any values."))
  232. }
  233. return topLevel
  234. }
  235. }
  236. // MARK: - __JSONEncoder
  237. // NOTE: older overlays called this class _JSONEncoder.
  238. // The two must coexist without a conflicting ObjC class name, so it
  239. // was renamed. The old name must not be used in the new runtime.
  240. fileprivate class __JSONEncoder : Encoder {
  241. // MARK: Properties
  242. /// The encoder's storage.
  243. fileprivate var storage: _JSONEncodingStorage
  244. /// Options set on the top-level encoder.
  245. fileprivate let options: FirebaseDataEncoder._Options
  246. /// The path to the current point in encoding.
  247. public var codingPath: [CodingKey]
  248. /// Contextual user-provided information for use during encoding.
  249. public var userInfo: [CodingUserInfoKey : Any] {
  250. return self.options.userInfo
  251. }
  252. // MARK: - Initialization
  253. /// Initializes `self` with the given top-level encoder options.
  254. fileprivate init(options: FirebaseDataEncoder._Options, codingPath: [CodingKey] = []) {
  255. self.options = options
  256. self.storage = _JSONEncodingStorage()
  257. self.codingPath = codingPath
  258. }
  259. /// Returns whether a new element can be encoded at this coding path.
  260. ///
  261. /// `true` if an element has not yet been encoded at this coding path; `false` otherwise.
  262. fileprivate var canEncodeNewValue: Bool {
  263. // Every time a new value gets encoded, the key it's encoded for is pushed onto the coding path (even if it's a nil key from an unkeyed container).
  264. // At the same time, every time a container is requested, a new value gets pushed onto the storage stack.
  265. // If there are more values on the storage stack than on the coding path, it means the value is requesting more than one container, which violates the precondition.
  266. //
  267. // This means that anytime something that can request a new container goes onto the stack, we MUST push a key onto the coding path.
  268. // Things which will not request containers do not need to have the coding path extended for them (but it doesn't matter if it is, because they will not reach here).
  269. return self.storage.count == self.codingPath.count
  270. }
  271. // MARK: - Encoder Methods
  272. public func container<Key>(keyedBy: Key.Type) -> KeyedEncodingContainer<Key> {
  273. // If an existing keyed container was already requested, return that one.
  274. let topContainer: NSMutableDictionary
  275. if self.canEncodeNewValue {
  276. // We haven't yet pushed a container at this level; do so here.
  277. topContainer = self.storage.pushKeyedContainer()
  278. } else {
  279. guard let container = self.storage.containers.last as? NSMutableDictionary else {
  280. preconditionFailure("Attempt to push new keyed encoding container when already previously encoded at this path.")
  281. }
  282. topContainer = container
  283. }
  284. let container = _JSONKeyedEncodingContainer<Key>(referencing: self, codingPath: self.codingPath, wrapping: topContainer)
  285. return KeyedEncodingContainer(container)
  286. }
  287. public func unkeyedContainer() -> UnkeyedEncodingContainer {
  288. // If an existing unkeyed container was already requested, return that one.
  289. let topContainer: NSMutableArray
  290. if self.canEncodeNewValue {
  291. // We haven't yet pushed a container at this level; do so here.
  292. topContainer = self.storage.pushUnkeyedContainer()
  293. } else {
  294. guard let container = self.storage.containers.last as? NSMutableArray else {
  295. preconditionFailure("Attempt to push new unkeyed encoding container when already previously encoded at this path.")
  296. }
  297. topContainer = container
  298. }
  299. return _JSONUnkeyedEncodingContainer(referencing: self, codingPath: self.codingPath, wrapping: topContainer)
  300. }
  301. public func singleValueContainer() -> SingleValueEncodingContainer {
  302. return self
  303. }
  304. }
  305. // MARK: - Encoding Storage and Containers
  306. fileprivate struct _JSONEncodingStorage {
  307. // MARK: Properties
  308. /// The container stack.
  309. /// Elements may be any one of the JSON types (NSNull, NSNumber, NSString, NSArray, NSDictionary).
  310. private(set) fileprivate var containers: [NSObject] = []
  311. // MARK: - Initialization
  312. /// Initializes `self` with no containers.
  313. fileprivate init() {}
  314. // MARK: - Modifying the Stack
  315. fileprivate var count: Int {
  316. return self.containers.count
  317. }
  318. fileprivate mutating func pushKeyedContainer() -> NSMutableDictionary {
  319. let dictionary = NSMutableDictionary()
  320. self.containers.append(dictionary)
  321. return dictionary
  322. }
  323. fileprivate mutating func pushUnkeyedContainer() -> NSMutableArray {
  324. let array = NSMutableArray()
  325. self.containers.append(array)
  326. return array
  327. }
  328. fileprivate mutating func push(container: __owned NSObject) {
  329. self.containers.append(container)
  330. }
  331. fileprivate mutating func popContainer() -> NSObject {
  332. precondition(!self.containers.isEmpty, "Empty container stack.")
  333. return self.containers.popLast()!
  334. }
  335. }
  336. // MARK: - Encoding Containers
  337. fileprivate struct _JSONKeyedEncodingContainer<K : CodingKey> : KeyedEncodingContainerProtocol {
  338. typealias Key = K
  339. // MARK: Properties
  340. /// A reference to the encoder we're writing to.
  341. private let encoder: __JSONEncoder
  342. /// A reference to the container we're writing to.
  343. private let container: NSMutableDictionary
  344. /// The path of coding keys taken to get to this point in encoding.
  345. private(set) public var codingPath: [CodingKey]
  346. // MARK: - Initialization
  347. /// Initializes `self` with the given references.
  348. fileprivate init(referencing encoder: __JSONEncoder, codingPath: [CodingKey], wrapping container: NSMutableDictionary) {
  349. self.encoder = encoder
  350. self.codingPath = codingPath
  351. self.container = container
  352. }
  353. // MARK: - Coding Path Operations
  354. private func _converted(_ key: CodingKey) -> CodingKey {
  355. switch encoder.options.keyEncodingStrategy {
  356. case .useDefaultKeys:
  357. return key
  358. case .convertToSnakeCase:
  359. let newKeyString = FirebaseDataEncoder.KeyEncodingStrategy._convertToSnakeCase(key.stringValue)
  360. return _JSONKey(stringValue: newKeyString, intValue: key.intValue)
  361. case .custom(let converter):
  362. return converter(codingPath + [key])
  363. }
  364. }
  365. // MARK: - KeyedEncodingContainerProtocol Methods
  366. public mutating func encodeNil(forKey key: Key) throws {
  367. self.container[_converted(key).stringValue] = NSNull()
  368. }
  369. public mutating func encode(_ value: Bool, forKey key: Key) throws {
  370. self.container[_converted(key).stringValue] = self.encoder.box(value)
  371. }
  372. public mutating func encode(_ value: Int, forKey key: Key) throws {
  373. self.container[_converted(key).stringValue] = self.encoder.box(value)
  374. }
  375. public mutating func encode(_ value: Int8, forKey key: Key) throws {
  376. self.container[_converted(key).stringValue] = self.encoder.box(value)
  377. }
  378. public mutating func encode(_ value: Int16, forKey key: Key) throws {
  379. self.container[_converted(key).stringValue] = self.encoder.box(value)
  380. }
  381. public mutating func encode(_ value: Int32, forKey key: Key) throws {
  382. self.container[_converted(key).stringValue] = self.encoder.box(value)
  383. }
  384. public mutating func encode(_ value: Int64, forKey key: Key) throws {
  385. self.container[_converted(key).stringValue] = self.encoder.box(value)
  386. }
  387. public mutating func encode(_ value: UInt, forKey key: Key) throws {
  388. self.container[_converted(key).stringValue] = self.encoder.box(value)
  389. }
  390. public mutating func encode(_ value: UInt8, forKey key: Key) throws {
  391. self.container[_converted(key).stringValue] = self.encoder.box(value)
  392. }
  393. public mutating func encode(_ value: UInt16, forKey key: Key) throws {
  394. self.container[_converted(key).stringValue] = self.encoder.box(value)
  395. }
  396. public mutating func encode(_ value: UInt32, forKey key: Key) throws {
  397. self.container[_converted(key).stringValue] = self.encoder.box(value)
  398. }
  399. public mutating func encode(_ value: UInt64, forKey key: Key) throws {
  400. self.container[_converted(key).stringValue] = self.encoder.box(value)
  401. }
  402. public mutating func encode(_ value: String, forKey key: Key) throws {
  403. self.container[_converted(key).stringValue] = self.encoder.box(value)
  404. }
  405. public mutating func encode(_ value: Float, forKey key: Key) throws {
  406. // Since the float may be invalid and throw, the coding path needs to contain this key.
  407. self.encoder.codingPath.append(key)
  408. defer { self.encoder.codingPath.removeLast() }
  409. self.container[_converted(key).stringValue] = try self.encoder.box(value)
  410. }
  411. public mutating func encode(_ value: Double, forKey key: Key) throws {
  412. // Since the double may be invalid and throw, the coding path needs to contain this key.
  413. self.encoder.codingPath.append(key)
  414. defer { self.encoder.codingPath.removeLast() }
  415. self.container[_converted(key).stringValue] = try self.encoder.box(value)
  416. }
  417. public mutating func encode<T : Encodable>(_ value: T, forKey key: Key) throws {
  418. self.encoder.codingPath.append(key)
  419. defer { self.encoder.codingPath.removeLast() }
  420. self.container[_converted(key).stringValue] = try self.encoder.box(value)
  421. }
  422. public mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> {
  423. let containerKey = _converted(key).stringValue
  424. let dictionary: NSMutableDictionary
  425. if let existingContainer = self.container[containerKey] {
  426. precondition(
  427. existingContainer is NSMutableDictionary,
  428. "Attempt to re-encode into nested KeyedEncodingContainer<\(Key.self)> for key \"\(containerKey)\" is invalid: non-keyed container already encoded for this key"
  429. )
  430. dictionary = existingContainer as! NSMutableDictionary
  431. } else {
  432. dictionary = NSMutableDictionary()
  433. self.container[containerKey] = dictionary
  434. }
  435. self.codingPath.append(key)
  436. defer { self.codingPath.removeLast() }
  437. let container = _JSONKeyedEncodingContainer<NestedKey>(referencing: self.encoder, codingPath: self.codingPath, wrapping: dictionary)
  438. return KeyedEncodingContainer(container)
  439. }
  440. public mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer {
  441. let containerKey = _converted(key).stringValue
  442. let array: NSMutableArray
  443. if let existingContainer = self.container[containerKey] {
  444. precondition(
  445. existingContainer is NSMutableArray,
  446. "Attempt to re-encode into nested UnkeyedEncodingContainer for key \"\(containerKey)\" is invalid: keyed container/single value already encoded for this key"
  447. )
  448. array = existingContainer as! NSMutableArray
  449. } else {
  450. array = NSMutableArray()
  451. self.container[containerKey] = array
  452. }
  453. self.codingPath.append(key)
  454. defer { self.codingPath.removeLast() }
  455. return _JSONUnkeyedEncodingContainer(referencing: self.encoder, codingPath: self.codingPath, wrapping: array)
  456. }
  457. public mutating func superEncoder() -> Encoder {
  458. return __JSONReferencingEncoder(referencing: self.encoder, key: _JSONKey.super, convertedKey: _converted(_JSONKey.super), wrapping: self.container)
  459. }
  460. public mutating func superEncoder(forKey key: Key) -> Encoder {
  461. return __JSONReferencingEncoder(referencing: self.encoder, key: key, convertedKey: _converted(key), wrapping: self.container)
  462. }
  463. }
  464. fileprivate struct _JSONUnkeyedEncodingContainer : UnkeyedEncodingContainer {
  465. // MARK: Properties
  466. /// A reference to the encoder we're writing to.
  467. private let encoder: __JSONEncoder
  468. /// A reference to the container we're writing to.
  469. private let container: NSMutableArray
  470. /// The path of coding keys taken to get to this point in encoding.
  471. private(set) public var codingPath: [CodingKey]
  472. /// The number of elements encoded into the container.
  473. public var count: Int {
  474. return self.container.count
  475. }
  476. // MARK: - Initialization
  477. /// Initializes `self` with the given references.
  478. fileprivate init(referencing encoder: __JSONEncoder, codingPath: [CodingKey], wrapping container: NSMutableArray) {
  479. self.encoder = encoder
  480. self.codingPath = codingPath
  481. self.container = container
  482. }
  483. // MARK: - UnkeyedEncodingContainer Methods
  484. public mutating func encodeNil() throws { self.container.add(NSNull()) }
  485. public mutating func encode(_ value: Bool) throws { self.container.add(self.encoder.box(value)) }
  486. public mutating func encode(_ value: Int) throws { self.container.add(self.encoder.box(value)) }
  487. public mutating func encode(_ value: Int8) throws { self.container.add(self.encoder.box(value)) }
  488. public mutating func encode(_ value: Int16) throws { self.container.add(self.encoder.box(value)) }
  489. public mutating func encode(_ value: Int32) throws { self.container.add(self.encoder.box(value)) }
  490. public mutating func encode(_ value: Int64) throws { self.container.add(self.encoder.box(value)) }
  491. public mutating func encode(_ value: UInt) throws { self.container.add(self.encoder.box(value)) }
  492. public mutating func encode(_ value: UInt8) throws { self.container.add(self.encoder.box(value)) }
  493. public mutating func encode(_ value: UInt16) throws { self.container.add(self.encoder.box(value)) }
  494. public mutating func encode(_ value: UInt32) throws { self.container.add(self.encoder.box(value)) }
  495. public mutating func encode(_ value: UInt64) throws { self.container.add(self.encoder.box(value)) }
  496. public mutating func encode(_ value: String) throws { self.container.add(self.encoder.box(value)) }
  497. public mutating func encode(_ value: Float) throws {
  498. // Since the float may be invalid and throw, the coding path needs to contain this key.
  499. self.encoder.codingPath.append(_JSONKey(index: self.count))
  500. defer { self.encoder.codingPath.removeLast() }
  501. self.container.add(try self.encoder.box(value))
  502. }
  503. public mutating func encode(_ value: Double) throws {
  504. // Since the double may be invalid and throw, the coding path needs to contain this key.
  505. self.encoder.codingPath.append(_JSONKey(index: self.count))
  506. defer { self.encoder.codingPath.removeLast() }
  507. self.container.add(try self.encoder.box(value))
  508. }
  509. public mutating func encode<T : Encodable>(_ value: T) throws {
  510. self.encoder.codingPath.append(_JSONKey(index: self.count))
  511. defer { self.encoder.codingPath.removeLast() }
  512. self.container.add(try self.encoder.box(value))
  513. }
  514. public mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> {
  515. self.codingPath.append(_JSONKey(index: self.count))
  516. defer { self.codingPath.removeLast() }
  517. let dictionary = NSMutableDictionary()
  518. self.container.add(dictionary)
  519. let container = _JSONKeyedEncodingContainer<NestedKey>(referencing: self.encoder, codingPath: self.codingPath, wrapping: dictionary)
  520. return KeyedEncodingContainer(container)
  521. }
  522. public mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer {
  523. self.codingPath.append(_JSONKey(index: self.count))
  524. defer { self.codingPath.removeLast() }
  525. let array = NSMutableArray()
  526. self.container.add(array)
  527. return _JSONUnkeyedEncodingContainer(referencing: self.encoder, codingPath: self.codingPath, wrapping: array)
  528. }
  529. public mutating func superEncoder() -> Encoder {
  530. return __JSONReferencingEncoder(referencing: self.encoder, at: self.container.count, wrapping: self.container)
  531. }
  532. }
  533. extension __JSONEncoder : SingleValueEncodingContainer {
  534. // MARK: - SingleValueEncodingContainer Methods
  535. fileprivate func assertCanEncodeNewValue() {
  536. precondition(self.canEncodeNewValue, "Attempt to encode value through single value container when previously value already encoded.")
  537. }
  538. public func encodeNil() throws {
  539. assertCanEncodeNewValue()
  540. self.storage.push(container: NSNull())
  541. }
  542. public func encode(_ value: Bool) throws {
  543. assertCanEncodeNewValue()
  544. self.storage.push(container: self.box(value))
  545. }
  546. public func encode(_ value: Int) throws {
  547. assertCanEncodeNewValue()
  548. self.storage.push(container: self.box(value))
  549. }
  550. public func encode(_ value: Int8) throws {
  551. assertCanEncodeNewValue()
  552. self.storage.push(container: self.box(value))
  553. }
  554. public func encode(_ value: Int16) throws {
  555. assertCanEncodeNewValue()
  556. self.storage.push(container: self.box(value))
  557. }
  558. public func encode(_ value: Int32) throws {
  559. assertCanEncodeNewValue()
  560. self.storage.push(container: self.box(value))
  561. }
  562. public func encode(_ value: Int64) throws {
  563. assertCanEncodeNewValue()
  564. self.storage.push(container: self.box(value))
  565. }
  566. public func encode(_ value: UInt) throws {
  567. assertCanEncodeNewValue()
  568. self.storage.push(container: self.box(value))
  569. }
  570. public func encode(_ value: UInt8) throws {
  571. assertCanEncodeNewValue()
  572. self.storage.push(container: self.box(value))
  573. }
  574. public func encode(_ value: UInt16) throws {
  575. assertCanEncodeNewValue()
  576. self.storage.push(container: self.box(value))
  577. }
  578. public func encode(_ value: UInt32) throws {
  579. assertCanEncodeNewValue()
  580. self.storage.push(container: self.box(value))
  581. }
  582. public func encode(_ value: UInt64) throws {
  583. assertCanEncodeNewValue()
  584. self.storage.push(container: self.box(value))
  585. }
  586. public func encode(_ value: String) throws {
  587. assertCanEncodeNewValue()
  588. self.storage.push(container: self.box(value))
  589. }
  590. public func encode(_ value: Float) throws {
  591. assertCanEncodeNewValue()
  592. try self.storage.push(container: self.box(value))
  593. }
  594. public func encode(_ value: Double) throws {
  595. assertCanEncodeNewValue()
  596. try self.storage.push(container: self.box(value))
  597. }
  598. public func encode<T : Encodable>(_ value: T) throws {
  599. assertCanEncodeNewValue()
  600. try self.storage.push(container: self.box(value))
  601. }
  602. }
  603. // MARK: - Concrete Value Representations
  604. extension __JSONEncoder {
  605. /// Returns the given value boxed in a container appropriate for pushing onto the container stack.
  606. fileprivate func box(_ value: Bool) -> NSObject { return NSNumber(value: value) }
  607. fileprivate func box(_ value: Int) -> NSObject { return NSNumber(value: value) }
  608. fileprivate func box(_ value: Int8) -> NSObject { return NSNumber(value: value) }
  609. fileprivate func box(_ value: Int16) -> NSObject { return NSNumber(value: value) }
  610. fileprivate func box(_ value: Int32) -> NSObject { return NSNumber(value: value) }
  611. fileprivate func box(_ value: Int64) -> NSObject { return NSNumber(value: value) }
  612. fileprivate func box(_ value: UInt) -> NSObject { return NSNumber(value: value) }
  613. fileprivate func box(_ value: UInt8) -> NSObject { return NSNumber(value: value) }
  614. fileprivate func box(_ value: UInt16) -> NSObject { return NSNumber(value: value) }
  615. fileprivate func box(_ value: UInt32) -> NSObject { return NSNumber(value: value) }
  616. fileprivate func box(_ value: UInt64) -> NSObject { return NSNumber(value: value) }
  617. fileprivate func box(_ value: String) -> NSObject { return NSString(string: value) }
  618. fileprivate func box(_ float: Float) throws -> NSObject {
  619. guard !float.isInfinite && !float.isNaN else {
  620. guard case let .convertToString(positiveInfinity: posInfString,
  621. negativeInfinity: negInfString,
  622. nan: nanString) = self.options.nonConformingFloatEncodingStrategy else {
  623. throw EncodingError._invalidFloatingPointValue(float, at: codingPath)
  624. }
  625. if float == Float.infinity {
  626. return NSString(string: posInfString)
  627. } else if float == -Float.infinity {
  628. return NSString(string: negInfString)
  629. } else {
  630. return NSString(string: nanString)
  631. }
  632. }
  633. return NSNumber(value: float)
  634. }
  635. fileprivate func box(_ double: Double) throws -> NSObject {
  636. guard !double.isInfinite && !double.isNaN else {
  637. guard case let .convertToString(positiveInfinity: posInfString,
  638. negativeInfinity: negInfString,
  639. nan: nanString) = self.options.nonConformingFloatEncodingStrategy else {
  640. throw EncodingError._invalidFloatingPointValue(double, at: codingPath)
  641. }
  642. if double == Double.infinity {
  643. return NSString(string: posInfString)
  644. } else if double == -Double.infinity {
  645. return NSString(string: negInfString)
  646. } else {
  647. return NSString(string: nanString)
  648. }
  649. }
  650. return NSNumber(value: double)
  651. }
  652. fileprivate func box(_ date: Date) throws -> NSObject {
  653. switch self.options.dateEncodingStrategy {
  654. case .deferredToDate:
  655. // Must be called with a surrounding with(pushedKey:) call.
  656. // Dates encode as single-value objects; this can't both throw and push a container, so no need to catch the error.
  657. try date.encode(to: self)
  658. return self.storage.popContainer()
  659. case .secondsSince1970:
  660. return NSNumber(value: date.timeIntervalSince1970)
  661. case .millisecondsSince1970:
  662. return NSNumber(value: 1000.0 * date.timeIntervalSince1970)
  663. case .iso8601:
  664. if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
  665. return NSString(string: _iso8601Formatter.string(from: date))
  666. } else {
  667. fatalError("ISO8601DateFormatter is unavailable on this platform.")
  668. }
  669. case .formatted(let formatter):
  670. return NSString(string: formatter.string(from: date))
  671. case .custom(let closure):
  672. let depth = self.storage.count
  673. do {
  674. try closure(date, self)
  675. } catch {
  676. // If the value pushed a container before throwing, pop it back off to restore state.
  677. if self.storage.count > depth {
  678. let _ = self.storage.popContainer()
  679. }
  680. throw error
  681. }
  682. guard self.storage.count > depth else {
  683. // The closure didn't encode anything. Return the default keyed container.
  684. return NSDictionary()
  685. }
  686. // We can pop because the closure encoded something.
  687. return self.storage.popContainer()
  688. }
  689. }
  690. fileprivate func box(_ data: Data) throws -> NSObject {
  691. switch self.options.dataEncodingStrategy {
  692. case .deferredToData:
  693. // Must be called with a surrounding with(pushedKey:) call.
  694. let depth = self.storage.count
  695. do {
  696. try data.encode(to: self)
  697. } catch {
  698. // If the value pushed a container before throwing, pop it back off to restore state.
  699. // This shouldn't be possible for Data (which encodes as an array of bytes), but it can't hurt to catch a failure.
  700. if self.storage.count > depth {
  701. let _ = self.storage.popContainer()
  702. }
  703. throw error
  704. }
  705. return self.storage.popContainer()
  706. case .base64:
  707. return NSString(string: data.base64EncodedString())
  708. case .custom(let closure):
  709. let depth = self.storage.count
  710. do {
  711. try closure(data, self)
  712. } catch {
  713. // If the value pushed a container before throwing, pop it back off to restore state.
  714. if self.storage.count > depth {
  715. let _ = self.storage.popContainer()
  716. }
  717. throw error
  718. }
  719. guard self.storage.count > depth else {
  720. // The closure didn't encode anything. Return the default keyed container.
  721. return NSDictionary()
  722. }
  723. // We can pop because the closure encoded something.
  724. return self.storage.popContainer()
  725. }
  726. }
  727. fileprivate func box(_ dict: [String : Encodable]) throws -> NSObject? {
  728. let depth = self.storage.count
  729. let result = self.storage.pushKeyedContainer()
  730. do {
  731. for (key, value) in dict {
  732. self.codingPath.append(_JSONKey(stringValue: key, intValue: nil))
  733. defer { self.codingPath.removeLast() }
  734. result[key] = try box(value)
  735. }
  736. } catch {
  737. // If the value pushed a container before throwing, pop it back off to restore state.
  738. if self.storage.count > depth {
  739. let _ = self.storage.popContainer()
  740. }
  741. throw error
  742. }
  743. // The top container should be a new container.
  744. guard self.storage.count > depth else {
  745. return nil
  746. }
  747. return self.storage.popContainer()
  748. }
  749. fileprivate func box(_ value: Encodable) throws -> NSObject {
  750. return try self.box_(value) ?? NSDictionary()
  751. }
  752. // This method is called "box_" instead of "box" to disambiguate it from the overloads. Because the return type here is different from all of the "box" overloads (and is more general), any "box" calls in here would call back into "box" recursively instead of calling the appropriate overload, which is not what we want.
  753. fileprivate func box_(_ value: Encodable) throws -> NSObject? {
  754. // Disambiguation between variable and function is required due to
  755. // issue tracked at: https://bugs.swift.org/browse/SR-1846
  756. let type = Swift.type(of: value)
  757. if type == Date.self || type == NSDate.self {
  758. // Respect Date encoding strategy
  759. return try self.box((value as! Date))
  760. } else if type == Data.self || type == NSData.self {
  761. // Respect Data encoding strategy
  762. return try self.box((value as! Data))
  763. } else if type == URL.self || type == NSURL.self {
  764. // Encode URLs as single strings.
  765. return self.box((value as! URL).absoluteString)
  766. } else if type == Decimal.self || type == NSDecimalNumber.self {
  767. // JSONSerialization can natively handle NSDecimalNumber.
  768. return (value as! NSDecimalNumber)
  769. } else if value is _JSONStringDictionaryEncodableMarker {
  770. return try self.box(value as! [String : Encodable])
  771. }
  772. // The value should request a container from the __JSONEncoder.
  773. let depth = self.storage.count
  774. do {
  775. try value.encode(to: self)
  776. } catch {
  777. // If the value pushed a container before throwing, pop it back off to restore state.
  778. if self.storage.count > depth {
  779. let _ = self.storage.popContainer()
  780. }
  781. throw error
  782. }
  783. // The top container should be a new container.
  784. guard self.storage.count > depth else {
  785. return nil
  786. }
  787. return self.storage.popContainer()
  788. }
  789. }
  790. // MARK: - __JSONReferencingEncoder
  791. /// __JSONReferencingEncoder is a special subclass of __JSONEncoder which has its own storage, but references the contents of a different encoder.
  792. /// It's used in superEncoder(), which returns a new encoder for encoding a superclass -- the lifetime of the encoder should not escape the scope it's created in, but it doesn't necessarily know when it's done being used (to write to the original container).
  793. // NOTE: older overlays called this class _JSONReferencingEncoder.
  794. // The two must coexist without a conflicting ObjC class name, so it
  795. // was renamed. The old name must not be used in the new runtime.
  796. fileprivate class __JSONReferencingEncoder : __JSONEncoder {
  797. // MARK: Reference types.
  798. /// The type of container we're referencing.
  799. private enum Reference {
  800. /// Referencing a specific index in an array container.
  801. case array(NSMutableArray, Int)
  802. /// Referencing a specific key in a dictionary container.
  803. case dictionary(NSMutableDictionary, String)
  804. }
  805. // MARK: - Properties
  806. /// The encoder we're referencing.
  807. fileprivate let encoder: __JSONEncoder
  808. /// The container reference itself.
  809. private let reference: Reference
  810. // MARK: - Initialization
  811. /// Initializes `self` by referencing the given array container in the given encoder.
  812. fileprivate init(referencing encoder: __JSONEncoder, at index: Int, wrapping array: NSMutableArray) {
  813. self.encoder = encoder
  814. self.reference = .array(array, index)
  815. super.init(options: encoder.options, codingPath: encoder.codingPath)
  816. self.codingPath.append(_JSONKey(index: index))
  817. }
  818. /// Initializes `self` by referencing the given dictionary container in the given encoder.
  819. fileprivate init(referencing encoder: __JSONEncoder,
  820. key: CodingKey, convertedKey: __shared CodingKey, wrapping dictionary: NSMutableDictionary) {
  821. self.encoder = encoder
  822. self.reference = .dictionary(dictionary, convertedKey.stringValue)
  823. super.init(options: encoder.options, codingPath: encoder.codingPath)
  824. self.codingPath.append(key)
  825. }
  826. // MARK: - Coding Path Operations
  827. fileprivate override var canEncodeNewValue: Bool {
  828. // With a regular encoder, the storage and coding path grow together.
  829. // A referencing encoder, however, inherits its parents coding path, as well as the key it was created for.
  830. // We have to take this into account.
  831. return self.storage.count == self.codingPath.count - self.encoder.codingPath.count - 1
  832. }
  833. // MARK: - Deinitialization
  834. // Finalizes `self` by writing the contents of our storage to the referenced encoder's storage.
  835. deinit {
  836. let value: Any
  837. switch self.storage.count {
  838. case 0: value = NSDictionary()
  839. case 1: value = self.storage.popContainer()
  840. default: fatalError("Referencing encoder deallocated with multiple containers on stack.")
  841. }
  842. switch self.reference {
  843. case .array(let array, let index):
  844. array.insert(value, at: index)
  845. case .dictionary(let dictionary, let key):
  846. dictionary[NSString(string: key)] = value
  847. }
  848. }
  849. }
  850. //===----------------------------------------------------------------------===//
  851. // JSON Decoder
  852. //===----------------------------------------------------------------------===//
  853. /// `JSONDecoder` facilitates the decoding of JSON into semantic `Decodable` types.
  854. // NOTE: older overlays had Foundation.JSONDecoder as the ObjC name.
  855. // The two must coexist, so it was renamed. The old name must not be
  856. // used in the new runtime. _TtC10Foundation13__JSONDecoder is the
  857. // mangled name for Foundation.__JSONDecoder.
  858. public class FirebaseDataDecoder {
  859. // MARK: Options
  860. /// The strategy to use for decoding `Date` values.
  861. public enum DateDecodingStrategy {
  862. /// Defer to `Date` for decoding. This is the default strategy.
  863. case deferredToDate
  864. /// Decode the `Date` as a UNIX timestamp from a JSON number.
  865. case secondsSince1970
  866. /// Decode the `Date` as UNIX millisecond timestamp from a JSON number.
  867. case millisecondsSince1970
  868. /// Decode the `Date` as an ISO-8601-formatted string (in RFC 3339 format).
  869. @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
  870. case iso8601
  871. /// Decode the `Date` as a string parsed by the given formatter.
  872. case formatted(DateFormatter)
  873. /// Decode the `Date` as a custom value decoded by the given closure.
  874. case custom((_ decoder: Swift.Decoder) throws -> Date)
  875. }
  876. /// The strategy to use for decoding `Data` values.
  877. public enum DataDecodingStrategy {
  878. /// Defer to `Data` for decoding.
  879. case deferredToData
  880. /// Decode the `Data` from a Base64-encoded string. This is the default strategy.
  881. case base64
  882. /// Decode the `Data` as a custom value decoded by the given closure.
  883. case custom((_ decoder: Swift.Decoder) throws -> Data)
  884. }
  885. /// The strategy to use for non-JSON-conforming floating-point values (IEEE 754 infinity and NaN).
  886. public enum NonConformingFloatDecodingStrategy {
  887. /// Throw upon encountering non-conforming values. This is the default strategy.
  888. case `throw`
  889. /// Decode the values from the given representation strings.
  890. case convertFromString(positiveInfinity: String, negativeInfinity: String, nan: String)
  891. }
  892. /// The strategy to use for automatically changing the value of keys before decoding.
  893. public enum KeyDecodingStrategy {
  894. /// Use the keys specified by each type. This is the default strategy.
  895. case useDefaultKeys
  896. /// Convert from "snake_case_keys" to "camelCaseKeys" before attempting to match a key with the one specified by each type.
  897. ///
  898. /// The conversion to upper case uses `Locale.system`, also known as the ICU "root" locale. This means the result is consistent regardless of the current user's locale and language preferences.
  899. ///
  900. /// Converting from snake case to camel case:
  901. /// 1. Capitalizes the word starting after each `_`
  902. /// 2. Removes all `_`
  903. /// 3. Preserves starting and ending `_` (as these are often used to indicate private variables or other metadata).
  904. /// For example, `one_two_three` becomes `oneTwoThree`. `_one_two_three_` becomes `_oneTwoThree_`.
  905. ///
  906. /// - Note: Using a key decoding strategy has a nominal performance cost, as each string key has to be inspected for the `_` character.
  907. case convertFromSnakeCase
  908. /// Provide a custom conversion from the key in the encoded JSON to the keys specified by the decoded types.
  909. /// The full path to the current decoding position is provided for context (in case you need to locate this key within the payload). The returned key is used in place of the last component in the coding path before decoding.
  910. /// If the result of the conversion is a duplicate key, then only one value will be present in the container for the type to decode from.
  911. case custom((_ codingPath: [CodingKey]) -> CodingKey)
  912. fileprivate static func _convertFromSnakeCase(_ stringKey: String) -> String {
  913. guard !stringKey.isEmpty else { return stringKey }
  914. // Find the first non-underscore character
  915. guard let firstNonUnderscore = stringKey.firstIndex(where: { $0 != "_" }) else {
  916. // Reached the end without finding an _
  917. return stringKey
  918. }
  919. // Find the last non-underscore character
  920. var lastNonUnderscore = stringKey.index(before: stringKey.endIndex)
  921. while lastNonUnderscore > firstNonUnderscore && stringKey[lastNonUnderscore] == "_" {
  922. stringKey.formIndex(before: &lastNonUnderscore)
  923. }
  924. let keyRange = firstNonUnderscore...lastNonUnderscore
  925. let leadingUnderscoreRange = stringKey.startIndex..<firstNonUnderscore
  926. let trailingUnderscoreRange = stringKey.index(after: lastNonUnderscore)..<stringKey.endIndex
  927. let components = stringKey[keyRange].split(separator: "_")
  928. let joinedString : String
  929. if components.count == 1 {
  930. // No underscores in key, leave the word as is - maybe already camel cased
  931. joinedString = String(stringKey[keyRange])
  932. } else {
  933. joinedString = ([components[0].lowercased()] + components[1...].map { $0.capitalized }).joined()
  934. }
  935. // Do a cheap isEmpty check before creating and appending potentially empty strings
  936. let result : String
  937. if (leadingUnderscoreRange.isEmpty && trailingUnderscoreRange.isEmpty) {
  938. result = joinedString
  939. } else if (!leadingUnderscoreRange.isEmpty && !trailingUnderscoreRange.isEmpty) {
  940. // Both leading and trailing underscores
  941. result = String(stringKey[leadingUnderscoreRange]) + joinedString + String(stringKey[trailingUnderscoreRange])
  942. } else if (!leadingUnderscoreRange.isEmpty) {
  943. // Just leading
  944. result = String(stringKey[leadingUnderscoreRange]) + joinedString
  945. } else {
  946. // Just trailing
  947. result = joinedString + String(stringKey[trailingUnderscoreRange])
  948. }
  949. return result
  950. }
  951. }
  952. /// The strategy to use in decoding dates. Defaults to `.deferredToDate`.
  953. open var dateDecodingStrategy: DateDecodingStrategy = .deferredToDate
  954. /// The strategy to use in decoding binary data. Defaults to `.base64`.
  955. open var dataDecodingStrategy: DataDecodingStrategy = .base64
  956. /// The strategy to use in decoding non-conforming numbers. Defaults to `.throw`.
  957. open var nonConformingFloatDecodingStrategy: NonConformingFloatDecodingStrategy = .throw
  958. /// The strategy to use for decoding keys. Defaults to `.useDefaultKeys`.
  959. open var keyDecodingStrategy: KeyDecodingStrategy = .useDefaultKeys
  960. /// Contextual user-provided information for use during decoding.
  961. open var userInfo: [CodingUserInfoKey : Any] = [:]
  962. /// Options set on the top-level encoder to pass down the decoding hierarchy.
  963. fileprivate struct _Options {
  964. let dateDecodingStrategy: DateDecodingStrategy
  965. let dataDecodingStrategy: DataDecodingStrategy
  966. let nonConformingFloatDecodingStrategy: NonConformingFloatDecodingStrategy
  967. let keyDecodingStrategy: KeyDecodingStrategy
  968. let userInfo: [CodingUserInfoKey : Any]
  969. }
  970. /// The options set on the top-level decoder.
  971. fileprivate var options: _Options {
  972. return _Options(dateDecodingStrategy: dateDecodingStrategy,
  973. dataDecodingStrategy: dataDecodingStrategy,
  974. nonConformingFloatDecodingStrategy: nonConformingFloatDecodingStrategy,
  975. keyDecodingStrategy: keyDecodingStrategy,
  976. userInfo: userInfo)
  977. }
  978. // MARK: - Constructing a JSON Decoder
  979. /// Initializes `self` with default strategies.
  980. public init() {}
  981. // MARK: - Decoding Values
  982. /// Decodes a top-level value of the given type from the given JSON representation.
  983. ///
  984. /// - parameter type: The type of the value to decode.
  985. /// - parameter data: The data to decode from.
  986. /// - returns: A value of the requested type.
  987. /// - throws: `DecodingError.dataCorrupted` if values requested from the payload are corrupted, or if the given data is not valid JSON.
  988. /// - throws: An error if any value throws an error during decoding.
  989. open func decode<T : Decodable>(_ type: T.Type, from structure: Any) throws -> T {
  990. let decoder = __JSONDecoder(referencing: structure, options: self.options)
  991. guard let value = try decoder.unbox(structure, as: type) else {
  992. throw Swift.DecodingError.valueNotFound(type, Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data did not contain a top-level value."))
  993. }
  994. return value
  995. }
  996. }
  997. // MARK: - __JSONDecoder
  998. // NOTE: older overlays called this class _JSONDecoder. The two must
  999. // coexist without a conflicting ObjC class name, so it was renamed.
  1000. // The old name must not be used in the new runtime.
  1001. fileprivate class __JSONDecoder : Decoder {
  1002. // MARK: Properties
  1003. /// The decoder's storage.
  1004. fileprivate var storage: _JSONDecodingStorage
  1005. /// Options set on the top-level decoder.
  1006. fileprivate let options: FirebaseDataDecoder._Options
  1007. /// The path to the current point in encoding.
  1008. fileprivate(set) public var codingPath: [CodingKey]
  1009. /// Contextual user-provided information for use during encoding.
  1010. public var userInfo: [CodingUserInfoKey : Any] {
  1011. return self.options.userInfo
  1012. }
  1013. // MARK: - Initialization
  1014. /// Initializes `self` with the given top-level container and options.
  1015. fileprivate init(referencing container: Any, at codingPath: [CodingKey] = [], options: FirebaseDataDecoder._Options) {
  1016. self.storage = _JSONDecodingStorage()
  1017. self.storage.push(container: container)
  1018. self.codingPath = codingPath
  1019. self.options = options
  1020. }
  1021. // MARK: - Decoder Methods
  1022. public func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
  1023. guard !(self.storage.topContainer is NSNull) else {
  1024. throw DecodingError.valueNotFound(KeyedDecodingContainer<Key>.self,
  1025. DecodingError.Context(codingPath: self.codingPath,
  1026. debugDescription: "Cannot get keyed decoding container -- found null value instead."))
  1027. }
  1028. var topContainer : [String : Any]
  1029. if let rcValue = self.storage.topContainer as? FirebaseRemoteConfigValueDecoding,
  1030. let top = rcValue.jsonValue() {
  1031. topContainer = top
  1032. } else {
  1033. guard let top = self.storage.topContainer as? [String : Any] else {
  1034. throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: self.storage.topContainer)
  1035. }
  1036. topContainer = top
  1037. }
  1038. let container = _JSONKeyedDecodingContainer<Key>(referencing: self, wrapping: topContainer)
  1039. return KeyedDecodingContainer(container)
  1040. }
  1041. public func unkeyedContainer() throws -> UnkeyedDecodingContainer {
  1042. guard !(self.storage.topContainer is NSNull) else {
  1043. throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self,
  1044. DecodingError.Context(codingPath: self.codingPath,
  1045. debugDescription: "Cannot get unkeyed decoding container -- found null value instead."))
  1046. }
  1047. guard let topContainer = self.storage.topContainer as? [Any] else {
  1048. throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: self.storage.topContainer)
  1049. }
  1050. return _JSONUnkeyedDecodingContainer(referencing: self, wrapping: topContainer)
  1051. }
  1052. public func singleValueContainer() throws -> SingleValueDecodingContainer {
  1053. return self
  1054. }
  1055. }
  1056. // MARK: - Decoding Storage
  1057. fileprivate struct _JSONDecodingStorage {
  1058. // MARK: Properties
  1059. /// The container stack.
  1060. /// Elements may be any one of the JSON types (NSNull, NSNumber, String, Array, [String : Any]).
  1061. private(set) fileprivate var containers: [Any] = []
  1062. // MARK: - Initialization
  1063. /// Initializes `self` with no containers.
  1064. fileprivate init() {}
  1065. // MARK: - Modifying the Stack
  1066. fileprivate var count: Int {
  1067. return self.containers.count
  1068. }
  1069. fileprivate var topContainer: Any {
  1070. precondition(!self.containers.isEmpty, "Empty container stack.")
  1071. return self.containers.last!
  1072. }
  1073. fileprivate mutating func push(container: __owned Any) {
  1074. self.containers.append(container)
  1075. }
  1076. fileprivate mutating func popContainer() {
  1077. precondition(!self.containers.isEmpty, "Empty container stack.")
  1078. self.containers.removeLast()
  1079. }
  1080. }
  1081. // MARK: Decoding Containers
  1082. fileprivate struct _JSONKeyedDecodingContainer<K : CodingKey> : KeyedDecodingContainerProtocol {
  1083. typealias Key = K
  1084. // MARK: Properties
  1085. /// A reference to the decoder we're reading from.
  1086. private let decoder: __JSONDecoder
  1087. /// A reference to the container we're reading from.
  1088. private let container: [String : Any]
  1089. /// The path of coding keys taken to get to this point in decoding.
  1090. private(set) public var codingPath: [CodingKey]
  1091. // MARK: - Initialization
  1092. /// Initializes `self` by referencing the given decoder and container.
  1093. fileprivate init(referencing decoder: __JSONDecoder, wrapping container: [String : Any]) {
  1094. self.decoder = decoder
  1095. switch decoder.options.keyDecodingStrategy {
  1096. case .useDefaultKeys:
  1097. self.container = container
  1098. case .convertFromSnakeCase:
  1099. // Convert the snake case keys in the container to camel case.
  1100. // If we hit a duplicate key after conversion, then we'll use the first one we saw. Effectively an undefined behavior with JSON dictionaries.
  1101. self.container = Dictionary(container.map {
  1102. key, value in (FirebaseDataDecoder.KeyDecodingStrategy._convertFromSnakeCase(key), value)
  1103. }, uniquingKeysWith: { (first, _) in first })
  1104. case .custom(let converter):
  1105. self.container = Dictionary(container.map {
  1106. key, value in (converter(decoder.codingPath + [_JSONKey(stringValue: key, intValue: nil)]).stringValue, value)
  1107. }, uniquingKeysWith: { (first, _) in first })
  1108. }
  1109. self.codingPath = decoder.codingPath
  1110. }
  1111. // MARK: - KeyedDecodingContainerProtocol Methods
  1112. public var allKeys: [Key] {
  1113. return self.container.keys.compactMap { Key(stringValue: $0) }
  1114. }
  1115. public func contains(_ key: Key) -> Bool {
  1116. return self.container[key.stringValue] != nil
  1117. }
  1118. private func _errorDescription(of key: CodingKey) -> String {
  1119. switch decoder.options.keyDecodingStrategy {
  1120. case .convertFromSnakeCase:
  1121. // In this case we can attempt to recover the original value by reversing the transform
  1122. let original = key.stringValue
  1123. let converted = FirebaseDataEncoder.KeyEncodingStrategy._convertToSnakeCase(original)
  1124. let roundtrip = FirebaseDataDecoder.KeyDecodingStrategy._convertFromSnakeCase(converted)
  1125. if converted == original {
  1126. return "\(key) (\"\(original)\")"
  1127. } else if roundtrip == original {
  1128. return "\(key) (\"\(original)\"), converted to \(converted)"
  1129. } else {
  1130. return "\(key) (\"\(original)\"), with divergent representation \(roundtrip), converted to \(converted)"
  1131. }
  1132. default:
  1133. // Otherwise, just report the converted string
  1134. return "\(key) (\"\(key.stringValue)\")"
  1135. }
  1136. }
  1137. public func decodeNil(forKey key: Key) throws -> Bool {
  1138. guard let entry = self.container[key.stringValue] else {
  1139. throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
  1140. }
  1141. return entry is NSNull
  1142. }
  1143. public func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool {
  1144. guard let entry = self.container[key.stringValue] else {
  1145. throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
  1146. }
  1147. self.decoder.codingPath.append(key)
  1148. defer { self.decoder.codingPath.removeLast() }
  1149. guard let value = try self.decoder.unbox(entry, as: Bool.self) else {
  1150. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
  1151. }
  1152. return value
  1153. }
  1154. public func decode(_ type: Int.Type, forKey key: Key) throws -> Int {
  1155. guard let entry = self.container[key.stringValue] else {
  1156. throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
  1157. }
  1158. self.decoder.codingPath.append(key)
  1159. defer { self.decoder.codingPath.removeLast() }
  1160. guard let value = try self.decoder.unbox(entry, as: Int.self) else {
  1161. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
  1162. }
  1163. return value
  1164. }
  1165. public func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 {
  1166. guard let entry = self.container[key.stringValue] else {
  1167. throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
  1168. }
  1169. self.decoder.codingPath.append(key)
  1170. defer { self.decoder.codingPath.removeLast() }
  1171. guard let value = try self.decoder.unbox(entry, as: Int8.self) else {
  1172. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
  1173. }
  1174. return value
  1175. }
  1176. public func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 {
  1177. guard let entry = self.container[key.stringValue] else {
  1178. throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
  1179. }
  1180. self.decoder.codingPath.append(key)
  1181. defer { self.decoder.codingPath.removeLast() }
  1182. guard let value = try self.decoder.unbox(entry, as: Int16.self) else {
  1183. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
  1184. }
  1185. return value
  1186. }
  1187. public func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 {
  1188. guard let entry = self.container[key.stringValue] else {
  1189. throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
  1190. }
  1191. self.decoder.codingPath.append(key)
  1192. defer { self.decoder.codingPath.removeLast() }
  1193. guard let value = try self.decoder.unbox(entry, as: Int32.self) else {
  1194. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
  1195. }
  1196. return value
  1197. }
  1198. public func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 {
  1199. guard let entry = self.container[key.stringValue] else {
  1200. throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
  1201. }
  1202. self.decoder.codingPath.append(key)
  1203. defer { self.decoder.codingPath.removeLast() }
  1204. guard let value = try self.decoder.unbox(entry, as: Int64.self) else {
  1205. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
  1206. }
  1207. return value
  1208. }
  1209. public func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt {
  1210. guard let entry = self.container[key.stringValue] else {
  1211. throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
  1212. }
  1213. self.decoder.codingPath.append(key)
  1214. defer { self.decoder.codingPath.removeLast() }
  1215. guard let value = try self.decoder.unbox(entry, as: UInt.self) else {
  1216. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
  1217. }
  1218. return value
  1219. }
  1220. public func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 {
  1221. guard let entry = self.container[key.stringValue] else {
  1222. throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
  1223. }
  1224. self.decoder.codingPath.append(key)
  1225. defer { self.decoder.codingPath.removeLast() }
  1226. guard let value = try self.decoder.unbox(entry, as: UInt8.self) else {
  1227. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
  1228. }
  1229. return value
  1230. }
  1231. public func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 {
  1232. guard let entry = self.container[key.stringValue] else {
  1233. throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
  1234. }
  1235. self.decoder.codingPath.append(key)
  1236. defer { self.decoder.codingPath.removeLast() }
  1237. guard let value = try self.decoder.unbox(entry, as: UInt16.self) else {
  1238. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
  1239. }
  1240. return value
  1241. }
  1242. public func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 {
  1243. guard let entry = self.container[key.stringValue] else {
  1244. throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
  1245. }
  1246. self.decoder.codingPath.append(key)
  1247. defer { self.decoder.codingPath.removeLast() }
  1248. guard let value = try self.decoder.unbox(entry, as: UInt32.self) else {
  1249. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
  1250. }
  1251. return value
  1252. }
  1253. public func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 {
  1254. guard let entry = self.container[key.stringValue] else {
  1255. throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
  1256. }
  1257. self.decoder.codingPath.append(key)
  1258. defer { self.decoder.codingPath.removeLast() }
  1259. guard let value = try self.decoder.unbox(entry, as: UInt64.self) else {
  1260. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
  1261. }
  1262. return value
  1263. }
  1264. public func decode(_ type: Float.Type, forKey key: Key) throws -> Float {
  1265. guard let entry = self.container[key.stringValue] else {
  1266. throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
  1267. }
  1268. self.decoder.codingPath.append(key)
  1269. defer { self.decoder.codingPath.removeLast() }
  1270. guard let value = try self.decoder.unbox(entry, as: Float.self) else {
  1271. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
  1272. }
  1273. return value
  1274. }
  1275. public func decode(_ type: Double.Type, forKey key: Key) throws -> Double {
  1276. guard let entry = self.container[key.stringValue] else {
  1277. throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
  1278. }
  1279. self.decoder.codingPath.append(key)
  1280. defer { self.decoder.codingPath.removeLast() }
  1281. guard let value = try self.decoder.unbox(entry, as: Double.self) else {
  1282. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
  1283. }
  1284. return value
  1285. }
  1286. public func decode(_ type: String.Type, forKey key: Key) throws -> String {
  1287. guard let entry = self.container[key.stringValue] else {
  1288. throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
  1289. }
  1290. self.decoder.codingPath.append(key)
  1291. defer { self.decoder.codingPath.removeLast() }
  1292. guard let value = try self.decoder.unbox(entry, as: String.self) else {
  1293. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
  1294. }
  1295. return value
  1296. }
  1297. public func decode<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T {
  1298. guard let entry = self.container[key.stringValue] else {
  1299. throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
  1300. }
  1301. self.decoder.codingPath.append(key)
  1302. defer { self.decoder.codingPath.removeLast() }
  1303. guard let value = try self.decoder.unbox(entry, as: type) else {
  1304. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
  1305. }
  1306. return value
  1307. }
  1308. public func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
  1309. self.decoder.codingPath.append(key)
  1310. defer { self.decoder.codingPath.removeLast() }
  1311. guard let value = self.container[key.stringValue] else {
  1312. throw DecodingError.keyNotFound(key,
  1313. DecodingError.Context(codingPath: self.codingPath,
  1314. debugDescription: "Cannot get \(KeyedDecodingContainer<NestedKey>.self) -- no value found for key \(_errorDescription(of: key))"))
  1315. }
  1316. guard let dictionary = value as? [String : Any] else {
  1317. throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: value)
  1318. }
  1319. let container = _JSONKeyedDecodingContainer<NestedKey>(referencing: self.decoder, wrapping: dictionary)
  1320. return KeyedDecodingContainer(container)
  1321. }
  1322. public func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
  1323. self.decoder.codingPath.append(key)
  1324. defer { self.decoder.codingPath.removeLast() }
  1325. guard let value = self.container[key.stringValue] else {
  1326. throw DecodingError.keyNotFound(key,
  1327. DecodingError.Context(codingPath: self.codingPath,
  1328. debugDescription: "Cannot get UnkeyedDecodingContainer -- no value found for key \(_errorDescription(of: key))"))
  1329. }
  1330. guard let array = value as? [Any] else {
  1331. throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: value)
  1332. }
  1333. return _JSONUnkeyedDecodingContainer(referencing: self.decoder, wrapping: array)
  1334. }
  1335. private func _superDecoder(forKey key: __owned CodingKey) throws -> Decoder {
  1336. self.decoder.codingPath.append(key)
  1337. defer { self.decoder.codingPath.removeLast() }
  1338. let value: Any = self.container[key.stringValue] ?? NSNull()
  1339. return __JSONDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options)
  1340. }
  1341. public func superDecoder() throws -> Decoder {
  1342. return try _superDecoder(forKey: _JSONKey.super)
  1343. }
  1344. public func superDecoder(forKey key: Key) throws -> Decoder {
  1345. return try _superDecoder(forKey: key)
  1346. }
  1347. }
  1348. fileprivate struct _JSONUnkeyedDecodingContainer : UnkeyedDecodingContainer {
  1349. // MARK: Properties
  1350. /// A reference to the decoder we're reading from.
  1351. private let decoder: __JSONDecoder
  1352. /// A reference to the container we're reading from.
  1353. private let container: [Any]
  1354. /// The path of coding keys taken to get to this point in decoding.
  1355. private(set) public var codingPath: [CodingKey]
  1356. /// The index of the element we're about to decode.
  1357. private(set) public var currentIndex: Int
  1358. // MARK: - Initialization
  1359. /// Initializes `self` by referencing the given decoder and container.
  1360. fileprivate init(referencing decoder: __JSONDecoder, wrapping container: [Any]) {
  1361. self.decoder = decoder
  1362. self.container = container
  1363. self.codingPath = decoder.codingPath
  1364. self.currentIndex = 0
  1365. }
  1366. // MARK: - UnkeyedDecodingContainer Methods
  1367. public var count: Int? {
  1368. return self.container.count
  1369. }
  1370. public var isAtEnd: Bool {
  1371. return self.currentIndex >= self.count!
  1372. }
  1373. public mutating func decodeNil() throws -> Bool {
  1374. guard !self.isAtEnd else {
  1375. throw DecodingError.valueNotFound(Any?.self, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
  1376. }
  1377. if self.container[self.currentIndex] is NSNull {
  1378. self.currentIndex += 1
  1379. return true
  1380. } else {
  1381. return false
  1382. }
  1383. }
  1384. public mutating func decode(_ type: Bool.Type) throws -> Bool {
  1385. guard !self.isAtEnd else {
  1386. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
  1387. }
  1388. self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
  1389. defer { self.decoder.codingPath.removeLast() }
  1390. guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Bool.self) else {
  1391. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
  1392. }
  1393. self.currentIndex += 1
  1394. return decoded
  1395. }
  1396. public mutating func decode(_ type: Int.Type) throws -> Int {
  1397. guard !self.isAtEnd else {
  1398. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
  1399. }
  1400. self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
  1401. defer { self.decoder.codingPath.removeLast() }
  1402. guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int.self) else {
  1403. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
  1404. }
  1405. self.currentIndex += 1
  1406. return decoded
  1407. }
  1408. public mutating func decode(_ type: Int8.Type) throws -> Int8 {
  1409. guard !self.isAtEnd else {
  1410. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
  1411. }
  1412. self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
  1413. defer { self.decoder.codingPath.removeLast() }
  1414. guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int8.self) else {
  1415. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
  1416. }
  1417. self.currentIndex += 1
  1418. return decoded
  1419. }
  1420. public mutating func decode(_ type: Int16.Type) throws -> Int16 {
  1421. guard !self.isAtEnd else {
  1422. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
  1423. }
  1424. self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
  1425. defer { self.decoder.codingPath.removeLast() }
  1426. guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int16.self) else {
  1427. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
  1428. }
  1429. self.currentIndex += 1
  1430. return decoded
  1431. }
  1432. public mutating func decode(_ type: Int32.Type) throws -> Int32 {
  1433. guard !self.isAtEnd else {
  1434. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
  1435. }
  1436. self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
  1437. defer { self.decoder.codingPath.removeLast() }
  1438. guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int32.self) else {
  1439. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
  1440. }
  1441. self.currentIndex += 1
  1442. return decoded
  1443. }
  1444. public mutating func decode(_ type: Int64.Type) throws -> Int64 {
  1445. guard !self.isAtEnd else {
  1446. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
  1447. }
  1448. self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
  1449. defer { self.decoder.codingPath.removeLast() }
  1450. guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int64.self) else {
  1451. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
  1452. }
  1453. self.currentIndex += 1
  1454. return decoded
  1455. }
  1456. public mutating func decode(_ type: UInt.Type) throws -> UInt {
  1457. guard !self.isAtEnd else {
  1458. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
  1459. }
  1460. self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
  1461. defer { self.decoder.codingPath.removeLast() }
  1462. guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt.self) else {
  1463. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
  1464. }
  1465. self.currentIndex += 1
  1466. return decoded
  1467. }
  1468. public mutating func decode(_ type: UInt8.Type) throws -> UInt8 {
  1469. guard !self.isAtEnd else {
  1470. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
  1471. }
  1472. self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
  1473. defer { self.decoder.codingPath.removeLast() }
  1474. guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt8.self) else {
  1475. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
  1476. }
  1477. self.currentIndex += 1
  1478. return decoded
  1479. }
  1480. public mutating func decode(_ type: UInt16.Type) throws -> UInt16 {
  1481. guard !self.isAtEnd else {
  1482. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
  1483. }
  1484. self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
  1485. defer { self.decoder.codingPath.removeLast() }
  1486. guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt16.self) else {
  1487. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
  1488. }
  1489. self.currentIndex += 1
  1490. return decoded
  1491. }
  1492. public mutating func decode(_ type: UInt32.Type) throws -> UInt32 {
  1493. guard !self.isAtEnd else {
  1494. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
  1495. }
  1496. self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
  1497. defer { self.decoder.codingPath.removeLast() }
  1498. guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt32.self) else {
  1499. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
  1500. }
  1501. self.currentIndex += 1
  1502. return decoded
  1503. }
  1504. public mutating func decode(_ type: UInt64.Type) throws -> UInt64 {
  1505. guard !self.isAtEnd else {
  1506. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
  1507. }
  1508. self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
  1509. defer { self.decoder.codingPath.removeLast() }
  1510. guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt64.self) else {
  1511. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
  1512. }
  1513. self.currentIndex += 1
  1514. return decoded
  1515. }
  1516. public mutating func decode(_ type: Float.Type) throws -> Float {
  1517. guard !self.isAtEnd else {
  1518. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
  1519. }
  1520. self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
  1521. defer { self.decoder.codingPath.removeLast() }
  1522. guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Float.self) else {
  1523. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
  1524. }
  1525. self.currentIndex += 1
  1526. return decoded
  1527. }
  1528. public mutating func decode(_ type: Double.Type) throws -> Double {
  1529. guard !self.isAtEnd else {
  1530. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
  1531. }
  1532. self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
  1533. defer { self.decoder.codingPath.removeLast() }
  1534. guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Double.self) else {
  1535. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
  1536. }
  1537. self.currentIndex += 1
  1538. return decoded
  1539. }
  1540. public mutating func decode(_ type: String.Type) throws -> String {
  1541. guard !self.isAtEnd else {
  1542. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
  1543. }
  1544. self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
  1545. defer { self.decoder.codingPath.removeLast() }
  1546. guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: String.self) else {
  1547. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
  1548. }
  1549. self.currentIndex += 1
  1550. return decoded
  1551. }
  1552. public mutating func decode<T : Decodable>(_ type: T.Type) throws -> T {
  1553. guard !self.isAtEnd else {
  1554. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
  1555. }
  1556. self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
  1557. defer { self.decoder.codingPath.removeLast() }
  1558. guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: type) else {
  1559. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
  1560. }
  1561. self.currentIndex += 1
  1562. return decoded
  1563. }
  1564. public mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> {
  1565. self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
  1566. defer { self.decoder.codingPath.removeLast() }
  1567. guard !self.isAtEnd else {
  1568. throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self,
  1569. DecodingError.Context(codingPath: self.codingPath,
  1570. debugDescription: "Cannot get nested keyed container -- unkeyed container is at end."))
  1571. }
  1572. let value = self.container[self.currentIndex]
  1573. guard !(value is NSNull) else {
  1574. throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self,
  1575. DecodingError.Context(codingPath: self.codingPath,
  1576. debugDescription: "Cannot get keyed decoding container -- found null value instead."))
  1577. }
  1578. guard let dictionary = value as? [String : Any] else {
  1579. throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: value)
  1580. }
  1581. self.currentIndex += 1
  1582. let container = _JSONKeyedDecodingContainer<NestedKey>(referencing: self.decoder, wrapping: dictionary)
  1583. return KeyedDecodingContainer(container)
  1584. }
  1585. public mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer {
  1586. self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
  1587. defer { self.decoder.codingPath.removeLast() }
  1588. guard !self.isAtEnd else {
  1589. throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self,
  1590. DecodingError.Context(codingPath: self.codingPath,
  1591. debugDescription: "Cannot get nested keyed container -- unkeyed container is at end."))
  1592. }
  1593. let value = self.container[self.currentIndex]
  1594. guard !(value is NSNull) else {
  1595. throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self,
  1596. DecodingError.Context(codingPath: self.codingPath,
  1597. debugDescription: "Cannot get keyed decoding container -- found null value instead."))
  1598. }
  1599. guard let array = value as? [Any] else {
  1600. throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: value)
  1601. }
  1602. self.currentIndex += 1
  1603. return _JSONUnkeyedDecodingContainer(referencing: self.decoder, wrapping: array)
  1604. }
  1605. public mutating func superDecoder() throws -> Decoder {
  1606. self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
  1607. defer { self.decoder.codingPath.removeLast() }
  1608. guard !self.isAtEnd else {
  1609. throw DecodingError.valueNotFound(Decoder.self,
  1610. DecodingError.Context(codingPath: self.codingPath,
  1611. debugDescription: "Cannot get superDecoder() -- unkeyed container is at end."))
  1612. }
  1613. let value = self.container[self.currentIndex]
  1614. self.currentIndex += 1
  1615. return __JSONDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options)
  1616. }
  1617. }
  1618. extension __JSONDecoder : SingleValueDecodingContainer {
  1619. // MARK: SingleValueDecodingContainer Methods
  1620. private func expectNonNull<T>(_ type: T.Type) throws {
  1621. guard !self.decodeNil() else {
  1622. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected \(type) but found null value instead."))
  1623. }
  1624. }
  1625. public func decodeNil() -> Bool {
  1626. return self.storage.topContainer is NSNull
  1627. }
  1628. public func decode(_ type: Bool.Type) throws -> Bool {
  1629. try expectNonNull(Bool.self)
  1630. return try self.unbox(self.storage.topContainer, as: Bool.self)!
  1631. }
  1632. public func decode(_ type: Int.Type) throws -> Int {
  1633. try expectNonNull(Int.self)
  1634. return try self.unbox(self.storage.topContainer, as: Int.self)!
  1635. }
  1636. public func decode(_ type: Int8.Type) throws -> Int8 {
  1637. try expectNonNull(Int8.self)
  1638. return try self.unbox(self.storage.topContainer, as: Int8.self)!
  1639. }
  1640. public func decode(_ type: Int16.Type) throws -> Int16 {
  1641. try expectNonNull(Int16.self)
  1642. return try self.unbox(self.storage.topContainer, as: Int16.self)!
  1643. }
  1644. public func decode(_ type: Int32.Type) throws -> Int32 {
  1645. try expectNonNull(Int32.self)
  1646. return try self.unbox(self.storage.topContainer, as: Int32.self)!
  1647. }
  1648. public func decode(_ type: Int64.Type) throws -> Int64 {
  1649. try expectNonNull(Int64.self)
  1650. return try self.unbox(self.storage.topContainer, as: Int64.self)!
  1651. }
  1652. public func decode(_ type: UInt.Type) throws -> UInt {
  1653. try expectNonNull(UInt.self)
  1654. return try self.unbox(self.storage.topContainer, as: UInt.self)!
  1655. }
  1656. public func decode(_ type: UInt8.Type) throws -> UInt8 {
  1657. try expectNonNull(UInt8.self)
  1658. return try self.unbox(self.storage.topContainer, as: UInt8.self)!
  1659. }
  1660. public func decode(_ type: UInt16.Type) throws -> UInt16 {
  1661. try expectNonNull(UInt16.self)
  1662. return try self.unbox(self.storage.topContainer, as: UInt16.self)!
  1663. }
  1664. public func decode(_ type: UInt32.Type) throws -> UInt32 {
  1665. try expectNonNull(UInt32.self)
  1666. return try self.unbox(self.storage.topContainer, as: UInt32.self)!
  1667. }
  1668. public func decode(_ type: UInt64.Type) throws -> UInt64 {
  1669. try expectNonNull(UInt64.self)
  1670. return try self.unbox(self.storage.topContainer, as: UInt64.self)!
  1671. }
  1672. public func decode(_ type: Float.Type) throws -> Float {
  1673. try expectNonNull(Float.self)
  1674. return try self.unbox(self.storage.topContainer, as: Float.self)!
  1675. }
  1676. public func decode(_ type: Double.Type) throws -> Double {
  1677. try expectNonNull(Double.self)
  1678. return try self.unbox(self.storage.topContainer, as: Double.self)!
  1679. }
  1680. public func decode(_ type: String.Type) throws -> String {
  1681. try expectNonNull(String.self)
  1682. return try self.unbox(self.storage.topContainer, as: String.self)!
  1683. }
  1684. public func decode<T : Decodable>(_ type: T.Type) throws -> T {
  1685. try expectNonNull(type)
  1686. return try self.unbox(self.storage.topContainer, as: type)!
  1687. }
  1688. }
  1689. // MARK: - Concrete Value Representations
  1690. extension __JSONDecoder {
  1691. /// Returns the given value unboxed from a container.
  1692. fileprivate func unbox(_ value: Any, as type: Bool.Type) throws -> Bool? {
  1693. guard !(value is NSNull) else { return nil }
  1694. if let rcValue = value as? FirebaseRemoteConfigValueDecoding {
  1695. return rcValue.boolValue()
  1696. }
  1697. if let number = value as? NSNumber {
  1698. // TODO: Add a flag to coerce non-boolean numbers into Bools?
  1699. if number === kCFBooleanTrue as NSNumber {
  1700. return true
  1701. } else if number === kCFBooleanFalse as NSNumber {
  1702. return false
  1703. }
  1704. /* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested:
  1705. } else if let bool = value as? Bool {
  1706. return bool
  1707. */
  1708. }
  1709. throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
  1710. }
  1711. fileprivate func rcValNumberAdaptor(_ value: Any) -> Any {
  1712. if let rcValue = value as? FirebaseRemoteConfigValueDecoding {
  1713. return rcValue.numberValue()
  1714. }
  1715. return value
  1716. }
  1717. fileprivate func getNumber(_ value: Any, as type: Any.Type) throws -> NSNumber {
  1718. let val = rcValNumberAdaptor(value)
  1719. guard let number = val as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
  1720. throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: val)
  1721. }
  1722. return number
  1723. }
  1724. fileprivate func unbox(_ value: Any, as type: Int.Type) throws -> Int? {
  1725. guard !(value is NSNull) else { return nil }
  1726. let number = try getNumber(value, as: type)
  1727. let int = number.intValue
  1728. guard NSNumber(value: int) == number else {
  1729. throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
  1730. }
  1731. return int
  1732. }
  1733. fileprivate func unbox(_ value: Any, as type: Int8.Type) throws -> Int8? {
  1734. guard !(value is NSNull) else { return nil }
  1735. let number = try getNumber(value, as: type)
  1736. let int8 = number.int8Value
  1737. guard NSNumber(value: int8) == number else {
  1738. throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
  1739. }
  1740. return int8
  1741. }
  1742. fileprivate func unbox(_ value: Any, as type: Int16.Type) throws -> Int16? {
  1743. guard !(value is NSNull) else { return nil }
  1744. let number = try getNumber(value, as: type)
  1745. let int16 = number.int16Value
  1746. guard NSNumber(value: int16) == number else {
  1747. throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
  1748. }
  1749. return int16
  1750. }
  1751. fileprivate func unbox(_ value: Any, as type: Int32.Type) throws -> Int32? {
  1752. guard !(value is NSNull) else { return nil }
  1753. let number = try getNumber(value, as: type)
  1754. let int32 = number.int32Value
  1755. guard NSNumber(value: int32) == number else {
  1756. throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
  1757. }
  1758. return int32
  1759. }
  1760. fileprivate func unbox(_ value: Any, as type: Int64.Type) throws -> Int64? {
  1761. guard !(value is NSNull) else { return nil }
  1762. let number = try getNumber(value, as: type)
  1763. let int64 = number.int64Value
  1764. guard NSNumber(value: int64) == number else {
  1765. throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
  1766. }
  1767. return int64
  1768. }
  1769. fileprivate func unbox(_ value: Any, as type: UInt.Type) throws -> UInt? {
  1770. guard !(value is NSNull) else { return nil }
  1771. let number = try getNumber(value, as: type)
  1772. let uint = number.uintValue
  1773. guard NSNumber(value: uint) == number else {
  1774. throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
  1775. }
  1776. return uint
  1777. }
  1778. fileprivate func unbox(_ value: Any, as type: UInt8.Type) throws -> UInt8? {
  1779. guard !(value is NSNull) else { return nil }
  1780. let number = try getNumber(value, as: type)
  1781. let uint8 = number.uint8Value
  1782. guard NSNumber(value: uint8) == number else {
  1783. throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
  1784. }
  1785. return uint8
  1786. }
  1787. fileprivate func unbox(_ value: Any, as type: UInt16.Type) throws -> UInt16? {
  1788. guard !(value is NSNull) else { return nil }
  1789. let number = try getNumber(value, as: type)
  1790. let uint16 = number.uint16Value
  1791. guard NSNumber(value: uint16) == number else {
  1792. throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
  1793. }
  1794. return uint16
  1795. }
  1796. fileprivate func unbox(_ value: Any, as type: UInt32.Type) throws -> UInt32? {
  1797. guard !(value is NSNull) else { return nil }
  1798. let number = try getNumber(value, as: type)
  1799. let uint32 = number.uint32Value
  1800. guard NSNumber(value: uint32) == number else {
  1801. throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
  1802. }
  1803. return uint32
  1804. }
  1805. fileprivate func unbox(_ value: Any, as type: UInt64.Type) throws -> UInt64? {
  1806. guard !(value is NSNull) else { return nil }
  1807. let number = try getNumber(value, as: type)
  1808. let uint64 = number.uint64Value
  1809. guard NSNumber(value: uint64) == number else {
  1810. throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
  1811. }
  1812. return uint64
  1813. }
  1814. fileprivate func unbox(_ value: Any, as type: Float.Type) throws -> Float? {
  1815. guard !(value is NSNull) else { return nil }
  1816. let val = rcValNumberAdaptor(value)
  1817. if let number = val as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse {
  1818. // We are willing to return a Float by losing precision:
  1819. // * If the original value was integral,
  1820. // * and the integral value was > Float.greatestFiniteMagnitude, we will fail
  1821. // * and the integral value was <= Float.greatestFiniteMagnitude, we are willing to lose precision past 2^24
  1822. // * If it was a Float, you will get back the precise value
  1823. // * If it was a Double or Decimal, you will get back the nearest approximation if it will fit
  1824. let double = number.doubleValue
  1825. guard abs(double) <= Double(Float.greatestFiniteMagnitude) else {
  1826. throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number \(number) does not fit in \(type)."))
  1827. }
  1828. return Float(double)
  1829. /* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested:
  1830. } else if let double = value as? Double {
  1831. if abs(double) <= Double(Float.max) {
  1832. return Float(double)
  1833. }
  1834. overflow = true
  1835. } else if let int = value as? Int {
  1836. if let float = Float(exactly: int) {
  1837. return float
  1838. }
  1839. overflow = true
  1840. */
  1841. } else if let string = val as? String,
  1842. case .convertFromString(let posInfString, let negInfString, let nanString) = self.options.nonConformingFloatDecodingStrategy {
  1843. if string == posInfString {
  1844. return Float.infinity
  1845. } else if string == negInfString {
  1846. return -Float.infinity
  1847. } else if string == nanString {
  1848. return Float.nan
  1849. }
  1850. }
  1851. throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
  1852. }
  1853. fileprivate func unbox(_ value: Any, as type: Double.Type) throws -> Double? {
  1854. guard !(value is NSNull) else { return nil }
  1855. let val = rcValNumberAdaptor(value)
  1856. if let number = val as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse {
  1857. // We are always willing to return the number as a Double:
  1858. // * If the original value was integral, it is guaranteed to fit in a Double; we are willing to lose precision past 2^53 if you encoded a UInt64 but requested a Double
  1859. // * If it was a Float or Double, you will get back the precise value
  1860. // * If it was Decimal, you will get back the nearest approximation
  1861. return number.doubleValue
  1862. /* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested:
  1863. } else if let double = value as? Double {
  1864. return double
  1865. } else if let int = value as? Int {
  1866. if let double = Double(exactly: int) {
  1867. return double
  1868. }
  1869. overflow = true
  1870. */
  1871. } else if let string = val as? String,
  1872. case .convertFromString(let posInfString, let negInfString, let nanString) = self.options.nonConformingFloatDecodingStrategy {
  1873. if string == posInfString {
  1874. return Double.infinity
  1875. } else if string == negInfString {
  1876. return -Double.infinity
  1877. } else if string == nanString {
  1878. return Double.nan
  1879. }
  1880. }
  1881. throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
  1882. }
  1883. fileprivate func unbox(_ value: Any, as type: String.Type) throws -> String? {
  1884. guard !(value is NSNull) else { return nil }
  1885. if let rcValue = value as? FirebaseRemoteConfigValueDecoding {
  1886. return rcValue.stringValue()
  1887. }
  1888. guard let string = value as? String else {
  1889. throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
  1890. }
  1891. return string
  1892. }
  1893. fileprivate func unbox(_ value: Any, as type: Date.Type) throws -> Date? {
  1894. guard !(value is NSNull) else { return nil }
  1895. switch self.options.dateDecodingStrategy {
  1896. case .deferredToDate:
  1897. self.storage.push(container: value)
  1898. defer { self.storage.popContainer() }
  1899. return try Date(from: self)
  1900. case .secondsSince1970:
  1901. let double = try self.unbox(value, as: Double.self)!
  1902. return Date(timeIntervalSince1970: double)
  1903. case .millisecondsSince1970:
  1904. let double = try self.unbox(value, as: Double.self)!
  1905. return Date(timeIntervalSince1970: double / 1000.0)
  1906. case .iso8601:
  1907. if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
  1908. let string = try self.unbox(value, as: String.self)!
  1909. guard let date = _iso8601Formatter.date(from: string) else {
  1910. throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected date string to be ISO8601-formatted."))
  1911. }
  1912. return date
  1913. } else {
  1914. fatalError("ISO8601DateFormatter is unavailable on this platform.")
  1915. }
  1916. case .formatted(let formatter):
  1917. let string = try self.unbox(value, as: String.self)!
  1918. guard let date = formatter.date(from: string) else {
  1919. throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Date string does not match format expected by formatter."))
  1920. }
  1921. return date
  1922. case .custom(let closure):
  1923. self.storage.push(container: value)
  1924. defer { self.storage.popContainer() }
  1925. return try closure(self)
  1926. }
  1927. }
  1928. fileprivate func unbox(_ value: Any, as type: Data.Type) throws -> Data? {
  1929. guard !(value is NSNull) else { return nil }
  1930. if let rcValue = value as? FirebaseRemoteConfigValueDecoding {
  1931. return rcValue.dataValue()
  1932. }
  1933. switch self.options.dataDecodingStrategy {
  1934. case .deferredToData:
  1935. self.storage.push(container: value)
  1936. defer { self.storage.popContainer() }
  1937. return try Data(from: self)
  1938. case .base64:
  1939. guard let string = value as? String else {
  1940. throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
  1941. }
  1942. guard let data = Data(base64Encoded: string) else {
  1943. throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Encountered Data is not valid Base64."))
  1944. }
  1945. return data
  1946. case .custom(let closure):
  1947. self.storage.push(container: value)
  1948. defer { self.storage.popContainer() }
  1949. return try closure(self)
  1950. }
  1951. }
  1952. fileprivate func unbox(_ value: Any, as type: Decimal.Type) throws -> Decimal? {
  1953. guard !(value is NSNull) else { return nil }
  1954. let val = rcValNumberAdaptor(value)
  1955. // Attempt to bridge from NSDecimalNumber.
  1956. if let decimal = val as? Decimal {
  1957. return decimal
  1958. } else {
  1959. let doubleValue = try self.unbox(val, as: Double.self)!
  1960. return Decimal(doubleValue)
  1961. }
  1962. }
  1963. fileprivate func unbox<T>(_ value: Any, as type: _JSONStringDictionaryDecodableMarker.Type) throws -> T? {
  1964. guard !(value is NSNull) else { return nil }
  1965. var result = [String : Any]()
  1966. guard let dict = value as? NSDictionary else {
  1967. throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
  1968. }
  1969. let elementType = type.elementType
  1970. for (key, value) in dict {
  1971. let key = key as! String
  1972. self.codingPath.append(_JSONKey(stringValue: key, intValue: nil))
  1973. defer { self.codingPath.removeLast() }
  1974. result[key] = try unbox_(value, as: elementType)
  1975. }
  1976. return result as? T
  1977. }
  1978. fileprivate func unbox<T : Decodable>(_ value: Any, as type: T.Type) throws -> T? {
  1979. return try unbox_(value, as: type) as? T
  1980. }
  1981. fileprivate func unbox_(_ value: Any, as type: Decodable.Type) throws -> Any? {
  1982. if type == Date.self || type == NSDate.self {
  1983. return try self.unbox(value, as: Date.self)
  1984. } else if type == Data.self || type == NSData.self {
  1985. return try self.unbox(value, as: Data.self)
  1986. } else if type == URL.self || type == NSURL.self {
  1987. guard let urlString = try self.unbox(value, as: String.self) else {
  1988. return nil
  1989. }
  1990. guard let url = URL(string: urlString) else {
  1991. throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath,
  1992. debugDescription: "Invalid URL string."))
  1993. }
  1994. return url
  1995. } else if type == Decimal.self || type == NSDecimalNumber.self {
  1996. return try self.unbox(value, as: Decimal.self)
  1997. } else if let stringKeyedDictType = type as? _JSONStringDictionaryDecodableMarker.Type {
  1998. return try self.unbox(value, as: stringKeyedDictType)
  1999. } else {
  2000. self.storage.push(container: value)
  2001. defer { self.storage.popContainer() }
  2002. return try type.init(from: self)
  2003. }
  2004. }
  2005. }
  2006. //===----------------------------------------------------------------------===//
  2007. // Shared Key Types
  2008. //===----------------------------------------------------------------------===//
  2009. fileprivate struct _JSONKey : CodingKey {
  2010. public var stringValue: String
  2011. public var intValue: Int?
  2012. public init?(stringValue: String) {
  2013. self.stringValue = stringValue
  2014. self.intValue = nil
  2015. }
  2016. public init?(intValue: Int) {
  2017. self.stringValue = "\(intValue)"
  2018. self.intValue = intValue
  2019. }
  2020. public init(stringValue: String, intValue: Int?) {
  2021. self.stringValue = stringValue
  2022. self.intValue = intValue
  2023. }
  2024. fileprivate init(index: Int) {
  2025. self.stringValue = "Index \(index)"
  2026. self.intValue = index
  2027. }
  2028. fileprivate static let `super` = _JSONKey(stringValue: "super")!
  2029. }
  2030. //===----------------------------------------------------------------------===//
  2031. // Shared ISO8601 Date Formatter
  2032. //===----------------------------------------------------------------------===//
  2033. // NOTE: This value is implicitly lazy and _must_ be lazy. We're compiled against the latest SDK (w/ ISO8601DateFormatter), but linked against whichever Foundation the user has. ISO8601DateFormatter might not exist, so we better not hit this code path on an older OS.
  2034. @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
  2035. fileprivate var _iso8601Formatter: ISO8601DateFormatter = {
  2036. let formatter = ISO8601DateFormatter()
  2037. formatter.formatOptions = .withInternetDateTime
  2038. return formatter
  2039. }()
  2040. //===----------------------------------------------------------------------===//
  2041. // Error Utilities
  2042. //===----------------------------------------------------------------------===//
  2043. extension EncodingError {
  2044. /// Returns a `.invalidValue` error describing the given invalid floating-point value.
  2045. ///
  2046. ///
  2047. /// - parameter value: The value that was invalid to encode.
  2048. /// - parameter path: The path of `CodingKey`s taken to encode this value.
  2049. /// - returns: An `EncodingError` with the appropriate path and debug description.
  2050. fileprivate static func _invalidFloatingPointValue<T : FloatingPoint>(_ value: T, at codingPath: [CodingKey]) -> EncodingError {
  2051. let valueDescription: String
  2052. if value == T.infinity {
  2053. valueDescription = "\(T.self).infinity"
  2054. } else if value == -T.infinity {
  2055. valueDescription = "-\(T.self).infinity"
  2056. } else {
  2057. valueDescription = "\(T.self).nan"
  2058. }
  2059. let debugDescription = "Unable to encode \(valueDescription) directly in JSON. Use JSONEncoder.NonConformingFloatEncodingStrategy.convertToString to specify how the value should be encoded."
  2060. return .invalidValue(value, EncodingError.Context(codingPath: codingPath, debugDescription: debugDescription))
  2061. }
  2062. }