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