FirebaseDataEncoder.swift 108 KB

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