FirestoreDecoder.swift 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  1. // This file is derived from swift/stdlib/public/SDK/Foundation/JSONEncoder.swift
  2. // and swift/stdlib/public/SDK/Foundation/PlistEncoder.swift
  3. //===----------------------------------------------------------------------===//
  4. //
  5. // This source file is part of the Swift.org open source project
  6. //
  7. // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
  8. // Licensed under Apache License v2.0 with Runtime Library Exception
  9. //
  10. // See https://swift.org/LICENSE.txt for license information
  11. // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
  12. //
  13. //===----------------------------------------------------------------------===//
  14. import FirebaseFirestore
  15. import Foundation
  16. extension Firestore {
  17. public struct Decoder {
  18. public init() {}
  19. /// Returns an instance of specified type from a Firestore document.
  20. ///
  21. /// If exists in `container`, Firestore specific types are recognized, and
  22. /// passed through to `Decodable` implementations. This means types below
  23. /// in `container` are directly supported:
  24. /// - GeoPoint
  25. /// - Timestamp
  26. /// - DocumentReference
  27. ///
  28. /// - Parameters:
  29. /// - A type to decode a document to.
  30. /// - container: A Map keyed of String representing a Firestore document.
  31. /// - Returns: An instance of specified type by the first parameter.
  32. public func decode<T: Decodable>(_: T.Type, from container: [String: Any]) throws -> T {
  33. let decoder = _FirestoreDecoder(referencing: container)
  34. guard let value = try decoder.unbox(container, as: T.self) else {
  35. throw DecodingError.valueNotFound(
  36. T.self,
  37. DecodingError.Context(codingPath: [],
  38. debugDescription: "The given dictionary was invalid")
  39. )
  40. }
  41. return value
  42. }
  43. }
  44. }
  45. class _FirestoreDecoder: Decoder {
  46. // `_FirestoreDecoder`
  47. // MARK: Properties
  48. /// A stack of data containers storing data containers to decode. When a new data
  49. /// container is being decoded, a corresponding storage is pushed to the stack;
  50. /// and when that container (and all of its children containers) has been decoded,
  51. /// it is popped out such that the decoding can proceed with new top storage.
  52. fileprivate var storage: _FirestoreDecodingStorage
  53. /// The path to the current point in the container tree. Given the root container, one could
  54. /// conceptually reconstruct `storage` by following `codingPath` from the root container.
  55. public fileprivate(set) var codingPath: [CodingKey]
  56. /// Contextual user-provided information for use during encoding.
  57. public var userInfo: [CodingUserInfoKey: Any] = [:]
  58. // MARK: - Initialization
  59. /// Initializes `self` with the given top-level container and options.
  60. init(referencing container: Any, at codingPath: [CodingKey] = []) {
  61. storage = _FirestoreDecodingStorage()
  62. storage.push(container: container)
  63. self.codingPath = codingPath
  64. }
  65. // MARK: - Decoder Methods
  66. public func container<Key>(keyedBy _: Key.Type) throws -> KeyedDecodingContainer<Key> {
  67. guard !(storage.topContainer is NSNull) else {
  68. throw DecodingError.valueNotFound(KeyedDecodingContainer<Key>.self,
  69. DecodingError.Context(codingPath: codingPath,
  70. debugDescription: "Cannot get keyed decoding container -- found null value instead."))
  71. }
  72. guard let topContainer = self.storage.topContainer as? [String: Any] else {
  73. let context = DecodingError.Context(codingPath: codingPath, debugDescription: "Not a dictionary")
  74. throw DecodingError.typeMismatch([String: Any].self, context)
  75. }
  76. let container = _FirestoreKeyedDecodingContainer<Key>(referencing: self, wrapping: topContainer)
  77. return KeyedDecodingContainer(container)
  78. }
  79. public func unkeyedContainer() throws -> UnkeyedDecodingContainer {
  80. guard !(storage.topContainer is NSNull) else {
  81. throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self,
  82. DecodingError.Context(codingPath: codingPath,
  83. debugDescription: "Cannot get unkeyed decoding container -- found null value instead."))
  84. }
  85. guard let topContainer = self.storage.topContainer as? [Any] else {
  86. let context = DecodingError.Context(codingPath: codingPath, debugDescription: "Not an array")
  87. throw DecodingError.typeMismatch([Any].self, context)
  88. }
  89. return _FirestoreUnkeyedDecodingContainer(referencing: self, wrapping: topContainer)
  90. }
  91. public func singleValueContainer() throws -> SingleValueDecodingContainer {
  92. return self
  93. }
  94. }
  95. private struct _FirestoreDecodingStorage {
  96. // MARK: Properties
  97. /// The container stack.
  98. /// Elements may be any one of the plist types (NSNumber, Date, String, Array, [String : Any]).
  99. fileprivate private(set) var containers: [Any] = []
  100. // MARK: - Initialization
  101. /// Initializes `self` with no containers.
  102. fileprivate init() {}
  103. // MARK: - Modifying the Stack
  104. fileprivate var count: Int {
  105. return containers.count
  106. }
  107. fileprivate var topContainer: Any {
  108. precondition(containers.count > 0, "Empty container stack.")
  109. return containers.last!
  110. }
  111. fileprivate mutating func push(container: Any) {
  112. containers.append(container)
  113. }
  114. fileprivate mutating func popContainer() {
  115. precondition(containers.count > 0, "Empty container stack.")
  116. containers.removeLast()
  117. }
  118. }
  119. private struct _FirestoreKeyedDecodingContainer<K: CodingKey>: KeyedDecodingContainerProtocol {
  120. typealias Key = K
  121. // MARK: Properties
  122. /// A reference to the decoder we're reading from.
  123. private let decoder: _FirestoreDecoder
  124. /// A reference to the container we're reading from.
  125. private let container: [String: Any]
  126. /// The path of coding keys taken to get to this point in decoding.
  127. public private(set) var codingPath: [CodingKey]
  128. // MARK: - Initialization
  129. /// Initializes `self` by referencing the given decoder and container.
  130. fileprivate init(referencing decoder: _FirestoreDecoder, wrapping container: [String: Any]) {
  131. self.decoder = decoder
  132. self.container = container
  133. codingPath = decoder.codingPath
  134. }
  135. // MARK: - KeyedDecodingContainerProtocol Methods
  136. public var allKeys: [Key] {
  137. return container.keys.compactMap { Key(stringValue: $0) }
  138. }
  139. public func contains(_ key: Key) -> Bool {
  140. return container[key.stringValue] != nil
  141. }
  142. public func decodeNil(forKey key: Key) throws -> Bool {
  143. let entry = try require(key: key)
  144. return entry is NSNull
  145. }
  146. public func decode(_: Bool.Type, forKey key: Key) throws -> Bool {
  147. let entry = try require(key: key)
  148. decoder.codingPath.append(key)
  149. defer { self.decoder.codingPath.removeLast() }
  150. let value = try decoder.unbox(entry, as: Bool.self)
  151. return try require(value: value)
  152. }
  153. public func decode(_: Int.Type, forKey key: Key) throws -> Int {
  154. let entry = try require(key: key)
  155. decoder.codingPath.append(key)
  156. defer { self.decoder.codingPath.removeLast() }
  157. let value = try decoder.unbox(entry, as: Int.self)
  158. return try require(value: value)
  159. }
  160. public func decode(_: Int8.Type, forKey key: Key) throws -> Int8 {
  161. let entry = try require(key: key)
  162. decoder.codingPath.append(key)
  163. defer { self.decoder.codingPath.removeLast() }
  164. let value = try decoder.unbox(entry, as: Int8.self)
  165. return try require(value: value)
  166. }
  167. public func decode(_: Int16.Type, forKey key: Key) throws -> Int16 {
  168. let entry = try require(key: key)
  169. decoder.codingPath.append(key)
  170. defer { self.decoder.codingPath.removeLast() }
  171. let value = try decoder.unbox(entry, as: Int16.self)
  172. return try require(value: value)
  173. }
  174. public func decode(_: Int32.Type, forKey key: Key) throws -> Int32 {
  175. let entry = try require(key: key)
  176. decoder.codingPath.append(key)
  177. defer { self.decoder.codingPath.removeLast() }
  178. let value = try decoder.unbox(entry, as: Int32.self)
  179. return try require(value: value)
  180. }
  181. public func decode(_: Int64.Type, forKey key: Key) throws -> Int64 {
  182. let entry = try require(key: key)
  183. decoder.codingPath.append(key)
  184. defer { self.decoder.codingPath.removeLast() }
  185. let value = try decoder.unbox(entry, as: Int64.self)
  186. return try require(value: value)
  187. }
  188. public func decode(_: UInt.Type, forKey key: Key) throws -> UInt {
  189. let entry = try require(key: key)
  190. decoder.codingPath.append(key)
  191. defer { self.decoder.codingPath.removeLast() }
  192. let value = try decoder.unbox(entry, as: UInt.self)
  193. return try require(value: value)
  194. }
  195. public func decode(_: UInt8.Type, forKey key: Key) throws -> UInt8 {
  196. let entry = try require(key: key)
  197. decoder.codingPath.append(key)
  198. defer { self.decoder.codingPath.removeLast() }
  199. let value = try decoder.unbox(entry, as: UInt8.self)
  200. return try require(value: value)
  201. }
  202. public func decode(_: UInt16.Type, forKey key: Key) throws -> UInt16 {
  203. let entry = try require(key: key)
  204. decoder.codingPath.append(key)
  205. defer { self.decoder.codingPath.removeLast() }
  206. let value = try decoder.unbox(entry, as: UInt16.self)
  207. return try require(value: value)
  208. }
  209. public func decode(_: UInt32.Type, forKey key: Key) throws -> UInt32 {
  210. let entry = try require(key: key)
  211. decoder.codingPath.append(key)
  212. defer { self.decoder.codingPath.removeLast() }
  213. let value = try decoder.unbox(entry, as: UInt32.self)
  214. return try require(value: value)
  215. }
  216. public func decode(_: UInt64.Type, forKey key: Key) throws -> UInt64 {
  217. let entry = try require(key: key)
  218. decoder.codingPath.append(key)
  219. defer { self.decoder.codingPath.removeLast() }
  220. let value = try decoder.unbox(entry, as: UInt64.self)
  221. return try require(value: value)
  222. }
  223. public func decode(_: Float.Type, forKey key: Key) throws -> Float {
  224. let entry = try require(key: key)
  225. decoder.codingPath.append(key)
  226. defer { self.decoder.codingPath.removeLast() }
  227. let value = try decoder.unbox(entry, as: Float.self)
  228. return try require(value: value)
  229. }
  230. public func decode(_: Double.Type, forKey key: Key) throws -> Double {
  231. let entry = try require(key: key)
  232. decoder.codingPath.append(key)
  233. defer { self.decoder.codingPath.removeLast() }
  234. let value = try decoder.unbox(entry, as: Double.self)
  235. return try require(value: value)
  236. }
  237. public func decode(_: String.Type, forKey key: Key) throws -> String {
  238. let entry = try require(key: key)
  239. decoder.codingPath.append(key)
  240. defer { self.decoder.codingPath.removeLast() }
  241. let value = try decoder.unbox(entry, as: String.self)
  242. return try require(value: value)
  243. }
  244. public func decode<T: Decodable>(_: T.Type, forKey key: Key) throws -> T {
  245. let entry = try require(key: key)
  246. decoder.codingPath.append(key)
  247. defer { self.decoder.codingPath.removeLast() }
  248. let value = try decoder.unbox(entry, as: T.self)
  249. return try require(value: value)
  250. }
  251. private func require(key: Key) throws -> Any {
  252. if let entry = self.container[key.stringValue] {
  253. return entry
  254. }
  255. let description = "No value associated with key \(key) (\"\(key.stringValue)\")."
  256. let context = DecodingError.Context(codingPath: decoder.codingPath, debugDescription: description)
  257. throw DecodingError.keyNotFound(key, context)
  258. }
  259. private func require<T>(value: T?) throws -> T {
  260. if let value = value {
  261. return value
  262. }
  263. let message = "Expected \(T.self) value but found null instead."
  264. let context = DecodingError.Context(codingPath: decoder.codingPath, debugDescription: message)
  265. throw DecodingError.valueNotFound(T.self, context)
  266. }
  267. public func nestedContainer<NestedKey>(keyedBy _: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
  268. decoder.codingPath.append(key)
  269. defer { self.decoder.codingPath.removeLast() }
  270. guard let value = self.container[key.stringValue] else {
  271. throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self,
  272. DecodingError.Context(codingPath: codingPath,
  273. debugDescription: "Cannot get nested keyed container -- no value found for key \"\(key.stringValue)\""))
  274. }
  275. guard let dictionary = value as? [String: Any] else {
  276. throw DecodingError._typeMismatch(at: codingPath, expectation: [String: Any].self, reality: value)
  277. }
  278. let container = _FirestoreKeyedDecodingContainer<NestedKey>(referencing: decoder, wrapping: dictionary)
  279. return KeyedDecodingContainer(container)
  280. }
  281. public func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
  282. decoder.codingPath.append(key)
  283. defer { self.decoder.codingPath.removeLast() }
  284. guard let value = self.container[key.stringValue] else {
  285. throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self,
  286. DecodingError.Context(codingPath: codingPath,
  287. debugDescription: "Cannot get nested unkeyed container -- no value found for key \"\(key.stringValue)\""))
  288. }
  289. guard let array = value as? [Any] else {
  290. let context = DecodingError.Context(codingPath: codingPath, debugDescription: "Not an array")
  291. throw DecodingError.typeMismatch([Any].self, context)
  292. }
  293. return _FirestoreUnkeyedDecodingContainer(referencing: decoder, wrapping: array)
  294. }
  295. private func _superDecoder(forKey key: CodingKey) throws -> Decoder {
  296. decoder.codingPath.append(key)
  297. defer { self.decoder.codingPath.removeLast() }
  298. let value: Any = container[key.stringValue] ?? NSNull()
  299. return _FirestoreDecoder(referencing: value, at: decoder.codingPath)
  300. }
  301. public func superDecoder() throws -> Decoder {
  302. return try _superDecoder(forKey: _FirestoreKey.super)
  303. }
  304. public func superDecoder(forKey key: Key) throws -> Decoder {
  305. return try _superDecoder(forKey: key)
  306. }
  307. }
  308. private struct _FirestoreUnkeyedDecodingContainer: UnkeyedDecodingContainer {
  309. // MARK: Properties
  310. /// A reference to the decoder we're reading from.
  311. private let decoder: _FirestoreDecoder
  312. /// A reference to the container we're reading from.
  313. private let container: [Any]
  314. /// The path of coding keys taken to get to this point in decoding.
  315. public private(set) var codingPath: [CodingKey]
  316. /// The index of the element we're about to decode.
  317. public private(set) var currentIndex: Int
  318. // MARK: - Initialization
  319. /// Initializes `self` by referencing the given decoder and container.
  320. fileprivate init(referencing decoder: _FirestoreDecoder, wrapping container: [Any]) {
  321. self.decoder = decoder
  322. self.container = container
  323. codingPath = decoder.codingPath
  324. currentIndex = 0
  325. }
  326. // MARK: - UnkeyedDecodingContainer Methods
  327. public var count: Int? {
  328. return container.count
  329. }
  330. public var isAtEnd: Bool {
  331. return currentIndex >= count!
  332. }
  333. public mutating func decodeNil() throws -> Bool {
  334. try expectNotAtEnd()
  335. if container[currentIndex] is NSNull {
  336. currentIndex += 1
  337. return true
  338. } else {
  339. return false
  340. }
  341. }
  342. public mutating func decode(_: Bool.Type) throws -> Bool {
  343. try expectNotAtEnd()
  344. decoder.codingPath.append(_FirestoreKey(index: currentIndex))
  345. defer { decoder.codingPath.removeLast() }
  346. let decoded = try decoder.unbox(container[currentIndex], as: Bool.self)
  347. return try require(value: decoded)
  348. }
  349. public mutating func decode(_: Int.Type) throws -> Int {
  350. try expectNotAtEnd()
  351. decoder.codingPath.append(_FirestoreKey(index: currentIndex))
  352. defer { decoder.codingPath.removeLast() }
  353. let decoded = try decoder.unbox(container[currentIndex], as: Int.self)
  354. return try require(value: decoded)
  355. }
  356. public mutating func decode(_: Int8.Type) throws -> Int8 {
  357. try expectNotAtEnd()
  358. decoder.codingPath.append(_FirestoreKey(index: currentIndex))
  359. defer { decoder.codingPath.removeLast() }
  360. let decoded = try decoder.unbox(container[currentIndex], as: Int8.self)
  361. return try require(value: decoded)
  362. }
  363. public mutating func decode(_: Int16.Type) throws -> Int16 {
  364. try expectNotAtEnd()
  365. decoder.codingPath.append(_FirestoreKey(index: currentIndex))
  366. defer { decoder.codingPath.removeLast() }
  367. let decoded = try decoder.unbox(container[currentIndex], as: Int16.self)
  368. return try require(value: decoded)
  369. }
  370. public mutating func decode(_: Int32.Type) throws -> Int32 {
  371. try expectNotAtEnd()
  372. decoder.codingPath.append(_FirestoreKey(index: currentIndex))
  373. defer { decoder.codingPath.removeLast() }
  374. let decoded = try decoder.unbox(container[currentIndex], as: Int32.self)
  375. return try require(value: decoded)
  376. }
  377. public mutating func decode(_: Int64.Type) throws -> Int64 {
  378. try expectNotAtEnd()
  379. decoder.codingPath.append(_FirestoreKey(index: currentIndex))
  380. defer { decoder.codingPath.removeLast() }
  381. let decoded = try decoder.unbox(container[currentIndex], as: Int64.self)
  382. return try require(value: decoded)
  383. }
  384. public mutating func decode(_: UInt.Type) throws -> UInt {
  385. try expectNotAtEnd()
  386. decoder.codingPath.append(_FirestoreKey(index: currentIndex))
  387. defer { decoder.codingPath.removeLast() }
  388. let decoded = try decoder.unbox(container[currentIndex], as: UInt.self)
  389. return try require(value: decoded)
  390. }
  391. public mutating func decode(_: UInt8.Type) throws -> UInt8 {
  392. try expectNotAtEnd()
  393. decoder.codingPath.append(_FirestoreKey(index: currentIndex))
  394. defer { decoder.codingPath.removeLast() }
  395. let decoded = try decoder.unbox(container[currentIndex], as: UInt8.self)
  396. return try require(value: decoded)
  397. }
  398. public mutating func decode(_: UInt16.Type) throws -> UInt16 {
  399. try expectNotAtEnd()
  400. decoder.codingPath.append(_FirestoreKey(index: currentIndex))
  401. defer { self.decoder.codingPath.removeLast() }
  402. let decoded = try decoder.unbox(container[currentIndex], as: UInt16.self)
  403. return try require(value: decoded)
  404. }
  405. public mutating func decode(_: UInt32.Type) throws -> UInt32 {
  406. try expectNotAtEnd()
  407. decoder.codingPath.append(_FirestoreKey(index: currentIndex))
  408. defer { decoder.codingPath.removeLast() }
  409. let decoded = try decoder.unbox(container[currentIndex], as: UInt32.self)
  410. return try require(value: decoded)
  411. }
  412. public mutating func decode(_: UInt64.Type) throws -> UInt64 {
  413. try expectNotAtEnd()
  414. decoder.codingPath.append(_FirestoreKey(index: currentIndex))
  415. defer { decoder.codingPath.removeLast() }
  416. let decoded = try decoder.unbox(container[currentIndex], as: UInt64.self)
  417. return try require(value: decoded)
  418. }
  419. public mutating func decode(_: Float.Type) throws -> Float {
  420. try expectNotAtEnd()
  421. decoder.codingPath.append(_FirestoreKey(index: currentIndex))
  422. defer { self.decoder.codingPath.removeLast() }
  423. let decoded = try decoder.unbox(container[currentIndex], as: Float.self)
  424. return try require(value: decoded)
  425. }
  426. public mutating func decode(_: Double.Type) throws -> Double {
  427. try expectNotAtEnd()
  428. decoder.codingPath.append(_FirestoreKey(index: currentIndex))
  429. defer { self.decoder.codingPath.removeLast() }
  430. let decoded = try decoder.unbox(container[currentIndex], as: Double.self)
  431. return try require(value: decoded)
  432. }
  433. public mutating func decode(_: String.Type) throws -> String {
  434. try expectNotAtEnd()
  435. decoder.codingPath.append(_FirestoreKey(index: currentIndex))
  436. defer { self.decoder.codingPath.removeLast() }
  437. let decoded = try decoder.unbox(container[currentIndex], as: String.self)
  438. return try require(value: decoded)
  439. }
  440. public mutating func decode<T: Decodable>(_: T.Type) throws -> T {
  441. try expectNotAtEnd()
  442. decoder.codingPath.append(_FirestoreKey(index: currentIndex))
  443. defer { self.decoder.codingPath.removeLast() }
  444. let decoded = try decoder.unbox(container[currentIndex], as: T.self)
  445. return try require(value: decoded)
  446. }
  447. public mutating func nestedContainer<NestedKey>(keyedBy _: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> {
  448. decoder.codingPath.append(_FirestoreKey(index: currentIndex))
  449. defer { self.decoder.codingPath.removeLast() }
  450. try expectNotAtEnd()
  451. let value = self.container[self.currentIndex]
  452. try requireNotNSNull(value)
  453. guard let dictionary = value as? [String: Any] else {
  454. throw DecodingError._typeMismatch(at: codingPath, expectation: [String: Any].self, reality: value)
  455. }
  456. currentIndex += 1
  457. let container = _FirestoreKeyedDecodingContainer<NestedKey>(referencing: decoder, wrapping: dictionary)
  458. return KeyedDecodingContainer(container)
  459. }
  460. public mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer {
  461. decoder.codingPath.append(_FirestoreKey(index: currentIndex))
  462. defer { self.decoder.codingPath.removeLast() }
  463. try expectNotAtEnd()
  464. let value = container[self.currentIndex]
  465. try requireNotNSNull(value)
  466. guard let array = value as? [Any] else {
  467. throw DecodingError._typeMismatch(at: codingPath, expectation: [Any].self, reality: value)
  468. }
  469. currentIndex += 1
  470. return _FirestoreUnkeyedDecodingContainer(referencing: decoder, wrapping: array)
  471. }
  472. public mutating func superDecoder() throws -> Decoder {
  473. decoder.codingPath.append(_FirestoreKey(index: currentIndex))
  474. defer { self.decoder.codingPath.removeLast() }
  475. try expectNotAtEnd()
  476. let value = container[self.currentIndex]
  477. currentIndex += 1
  478. return _FirestoreDecoder(referencing: value, at: decoder.codingPath)
  479. }
  480. private func expectNotAtEnd() throws {
  481. guard !isAtEnd else {
  482. throw DecodingError.valueNotFound(Any?.self, DecodingError.Context(codingPath: decoder.codingPath + [_FirestoreKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
  483. }
  484. }
  485. private func requireNotNSNull(_ value: Any) throws {
  486. if !(value is NSNull) {
  487. return
  488. }
  489. let description = "Cannot get keyed decoding container -- found null value instead."
  490. let context = DecodingError.Context(codingPath: codingPath, debugDescription: description)
  491. throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, context)
  492. }
  493. private mutating func require<T>(value: T?) throws -> T {
  494. guard let value = value else {
  495. let message = "Expected \(T.self) value but found null instead."
  496. let context = DecodingError.Context(codingPath: decoder.codingPath + [_FirestoreKey(index: currentIndex)], debugDescription: message)
  497. throw DecodingError.valueNotFound(T.self, context)
  498. }
  499. currentIndex += 1
  500. return value
  501. }
  502. }
  503. extension _FirestoreDecoder: SingleValueDecodingContainer {
  504. // MARK: SingleValueDecodingContainer Methods
  505. private func expectNonNull<T>(_ type: T.Type) throws {
  506. guard !decodeNil() else {
  507. throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) but found null value instead."))
  508. }
  509. }
  510. public func decodeNil() -> Bool {
  511. return storage.topContainer is NSNull
  512. }
  513. public func decode(_: Bool.Type) throws -> Bool {
  514. try expectNonNull(Bool.self)
  515. return try unbox(storage.topContainer, as: Bool.self)!
  516. }
  517. public func decode(_: Int.Type) throws -> Int {
  518. try expectNonNull(Int.self)
  519. return try unbox(storage.topContainer, as: Int.self)!
  520. }
  521. public func decode(_: Int8.Type) throws -> Int8 {
  522. try expectNonNull(Int8.self)
  523. return try unbox(storage.topContainer, as: Int8.self)!
  524. }
  525. public func decode(_: Int16.Type) throws -> Int16 {
  526. try expectNonNull(Int16.self)
  527. return try unbox(storage.topContainer, as: Int16.self)!
  528. }
  529. public func decode(_: Int32.Type) throws -> Int32 {
  530. try expectNonNull(Int32.self)
  531. return try unbox(storage.topContainer, as: Int32.self)!
  532. }
  533. public func decode(_: Int64.Type) throws -> Int64 {
  534. try expectNonNull(Int64.self)
  535. return try unbox(storage.topContainer, as: Int64.self)!
  536. }
  537. public func decode(_: UInt.Type) throws -> UInt {
  538. try expectNonNull(UInt.self)
  539. return try unbox(storage.topContainer, as: UInt.self)!
  540. }
  541. public func decode(_: UInt8.Type) throws -> UInt8 {
  542. try expectNonNull(UInt8.self)
  543. return try unbox(storage.topContainer, as: UInt8.self)!
  544. }
  545. public func decode(_: UInt16.Type) throws -> UInt16 {
  546. try expectNonNull(UInt16.self)
  547. return try unbox(storage.topContainer, as: UInt16.self)!
  548. }
  549. public func decode(_: UInt32.Type) throws -> UInt32 {
  550. try expectNonNull(UInt32.self)
  551. return try unbox(storage.topContainer, as: UInt32.self)!
  552. }
  553. public func decode(_: UInt64.Type) throws -> UInt64 {
  554. try expectNonNull(UInt64.self)
  555. return try unbox(storage.topContainer, as: UInt64.self)!
  556. }
  557. public func decode(_: Float.Type) throws -> Float {
  558. try expectNonNull(Float.self)
  559. return try unbox(storage.topContainer, as: Float.self)!
  560. }
  561. public func decode(_: Double.Type) throws -> Double {
  562. try expectNonNull(Double.self)
  563. return try unbox(storage.topContainer, as: Double.self)!
  564. }
  565. public func decode(_: String.Type) throws -> String {
  566. try expectNonNull(String.self)
  567. return try unbox(storage.topContainer, as: String.self)!
  568. }
  569. public func decode<T: Decodable>(_: T.Type) throws -> T {
  570. try expectNonNull(T.self)
  571. return try unbox(storage.topContainer, as: T.self)!
  572. }
  573. }
  574. extension _FirestoreDecoder {
  575. /// Returns the given value unboxed from a container.
  576. func unbox(_ value: Any, as type: Bool.Type) throws -> Bool? {
  577. guard !(value is NSNull) else { return nil }
  578. if let number = value as? NSNumber {
  579. // TODO: Add a flag to coerce non-boolean numbers into Bools?
  580. if number === kCFBooleanTrue as NSNumber {
  581. return true
  582. } else if number === kCFBooleanFalse as NSNumber {
  583. return false
  584. }
  585. }
  586. throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
  587. }
  588. func unbox(_ value: Any, as type: Int.Type) throws -> Int? {
  589. guard !(value is NSNull) else { return nil }
  590. guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
  591. throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
  592. }
  593. let int = number.intValue
  594. guard NSNumber(value: int) == number else {
  595. throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Decoded number <\(number)> does not fit in \(type)."))
  596. }
  597. return int
  598. }
  599. func unbox(_ value: Any, as type: Int8.Type) throws -> Int8? {
  600. guard !(value is NSNull) else { return nil }
  601. guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
  602. throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
  603. }
  604. let int8 = number.int8Value
  605. guard NSNumber(value: int8) == number else {
  606. throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Decoded number <\(number)> does not fit in \(type)."))
  607. }
  608. return int8
  609. }
  610. func unbox(_ value: Any, as type: Int16.Type) throws -> Int16? {
  611. guard !(value is NSNull) else { return nil }
  612. guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
  613. throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
  614. }
  615. let int16 = number.int16Value
  616. guard NSNumber(value: int16) == number else {
  617. throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Decoded number <\(number)> does not fit in \(type)."))
  618. }
  619. return int16
  620. }
  621. func unbox(_ value: Any, as type: Int32.Type) throws -> Int32? {
  622. guard !(value is NSNull) else { return nil }
  623. guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
  624. throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
  625. }
  626. let int32 = number.int32Value
  627. guard NSNumber(value: int32) == number else {
  628. throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Decoded number <\(number)> does not fit in \(type)."))
  629. }
  630. return int32
  631. }
  632. func unbox(_ value: Any, as type: Int64.Type) throws -> Int64? {
  633. guard !(value is NSNull) else { return nil }
  634. guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
  635. throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
  636. }
  637. let int64 = number.int64Value
  638. guard NSNumber(value: int64) == number else {
  639. throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Decoded number <\(number)> does not fit in \(type)."))
  640. }
  641. return int64
  642. }
  643. func unbox(_ value: Any, as type: UInt.Type) throws -> UInt? {
  644. guard !(value is NSNull) else { return nil }
  645. guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
  646. throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
  647. }
  648. let uint = number.uintValue
  649. guard NSNumber(value: uint) == number else {
  650. throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Decoded number <\(number)> does not fit in \(type)."))
  651. }
  652. return uint
  653. }
  654. func unbox(_ value: Any, as type: UInt8.Type) throws -> UInt8? {
  655. guard !(value is NSNull) else { return nil }
  656. guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
  657. throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
  658. }
  659. let uint8 = number.uint8Value
  660. guard NSNumber(value: uint8) == number else {
  661. throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Decoded number <\(number)> does not fit in \(type)."))
  662. }
  663. return uint8
  664. }
  665. func unbox(_ value: Any, as type: UInt16.Type) throws -> UInt16? {
  666. guard !(value is NSNull) else { return nil }
  667. guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
  668. throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
  669. }
  670. let uint16 = number.uint16Value
  671. guard NSNumber(value: uint16) == number else {
  672. throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Decoded number <\(number)> does not fit in \(type)."))
  673. }
  674. return uint16
  675. }
  676. func unbox(_ value: Any, as type: UInt32.Type) throws -> UInt32? {
  677. guard !(value is NSNull) else { return nil }
  678. guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
  679. throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
  680. }
  681. let uint32 = number.uint32Value
  682. guard NSNumber(value: uint32) == number else {
  683. throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Decoded number <\(number)> does not fit in \(type)."))
  684. }
  685. return uint32
  686. }
  687. func unbox(_ value: Any, as type: UInt64.Type) throws -> UInt64? {
  688. guard !(value is NSNull) else { return nil }
  689. guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
  690. throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
  691. }
  692. let uint64 = number.uint64Value
  693. guard NSNumber(value: uint64) == number else {
  694. throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Decoded number <\(number)> does not fit in \(type)."))
  695. }
  696. return uint64
  697. }
  698. func unbox(_ value: Any, as type: Float.Type) throws -> Float? {
  699. guard !(value is NSNull) else { return nil }
  700. if let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse {
  701. // We are willing to return a Float by losing precision:
  702. // * If the original value was integral,
  703. // * and the integral value was > Float.greatestFiniteMagnitude, we will fail
  704. // * and the integral value was <= Float.greatestFiniteMagnitude, we are willing to lose precision past 2^24
  705. // * If it was a Float, you will get back the precise value
  706. // * If it was a Double or Decimal, you will get back the nearest approximation if it will fit
  707. let double = number.doubleValue
  708. guard abs(double) <= Double(Float.greatestFiniteMagnitude) else {
  709. throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Decoded number \(number) does not fit in \(type)."))
  710. }
  711. return Float(double)
  712. }
  713. throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
  714. }
  715. func unbox(_ value: Any, as type: Double.Type) throws -> Double? {
  716. guard !(value is NSNull) else { return nil }
  717. if let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse {
  718. // We are always willing to return the number as a Double:
  719. // * 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
  720. // * If it was a Float or Double, you will get back the precise value
  721. // * If it was Decimal, you will get back the nearest approximation
  722. return number.doubleValue
  723. }
  724. throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
  725. }
  726. func unbox(_ value: Any, as type: String.Type) throws -> String? {
  727. guard !(value is NSNull) else { return nil }
  728. guard let string = value as? String else {
  729. throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
  730. }
  731. return string
  732. }
  733. func unbox(_ value: Any, as type: Date.Type) throws -> Date? {
  734. guard !(value is NSNull) else { return nil }
  735. guard let date = value as? Date else {
  736. throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
  737. }
  738. return date
  739. }
  740. func unbox(_ value: Any, as type: Data.Type) throws -> Data? {
  741. guard !(value is NSNull) else { return nil }
  742. guard let data = value as? Data else {
  743. throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
  744. }
  745. return data
  746. }
  747. func unbox(_ value: Any, as _: Decimal.Type) throws -> Decimal? {
  748. guard !(value is NSNull) else { return nil }
  749. // Attempt to bridge from NSDecimalNumber.
  750. if let decimal = value as? Decimal {
  751. return decimal
  752. } else {
  753. let doubleValue = try unbox(value, as: Double.self)!
  754. return Decimal(doubleValue)
  755. }
  756. }
  757. func unbox<T: Decodable>(_ value: Any, as _: T.Type) throws -> T? {
  758. if T.self == Date.self || T.self == NSDate.self {
  759. guard let date = try self.unbox(value, as: Date.self) else { return nil }
  760. return (date as! T)
  761. }
  762. if T.self == Data.self || T.self == NSData.self {
  763. guard let data = try self.unbox(value, as: Data.self) else { return nil }
  764. return (data as! T)
  765. }
  766. if T.self == URL.self || T.self == NSURL.self {
  767. guard let urlString = try self.unbox(value, as: String.self) else {
  768. return nil
  769. }
  770. guard let url = URL(string: urlString) else {
  771. throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath,
  772. debugDescription: "Invalid URL string."))
  773. }
  774. return (url as! T)
  775. }
  776. if T.self == Decimal.self || T.self == NSDecimalNumber.self {
  777. guard let decimal = try self.unbox(value, as: Decimal.self) else { return nil }
  778. return (decimal as! T)
  779. }
  780. if let v = value as? T {
  781. if isFirestorePassthroughType(v) {
  782. // All the native Firestore types that should not be encoded
  783. return (value as! T)
  784. }
  785. }
  786. // Decoding an embedded container, this requires expanding the storage stack and
  787. // then restore after decoding.
  788. storage.push(container: value)
  789. let decoded = try T(from: self)
  790. storage.popContainer()
  791. return decoded
  792. }
  793. }
  794. extension DecodingError {
  795. static func _typeMismatch(at path: [CodingKey], expectation: Any.Type, reality: Any) -> DecodingError {
  796. let description = "Expected to decode \(expectation) but found \(_typeDescription(of: reality)) instead."
  797. return .typeMismatch(expectation, Context(codingPath: path, debugDescription: description))
  798. }
  799. fileprivate static func _typeDescription(of value: Any) -> String {
  800. if value is NSNull {
  801. return "a null value"
  802. } 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 */ {
  803. return "a number"
  804. } else if value is String {
  805. return "a string/data"
  806. } else if value is [Any] {
  807. return "an array"
  808. } else if value is [String: Any] {
  809. return "a dictionary"
  810. } else {
  811. return "\(type(of: value))"
  812. }
  813. }
  814. }