FirestoreDecoder.swift 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  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. // Firestore returns all dates as Timestamp, converting it to Date so it can be used in custom objects.
  736. if let timestamp = value as? Timestamp {
  737. return timestamp.dateValue()
  738. }
  739. guard let date = value as? Date else {
  740. throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
  741. }
  742. return date
  743. }
  744. func unbox(_ value: Any, as type: Data.Type) throws -> Data? {
  745. guard !(value is NSNull) else { return nil }
  746. guard let data = value as? Data else {
  747. throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value)
  748. }
  749. return data
  750. }
  751. func unbox(_ value: Any, as _: Decimal.Type) throws -> Decimal? {
  752. guard !(value is NSNull) else { return nil }
  753. // Attempt to bridge from NSDecimalNumber.
  754. if let decimal = value as? Decimal {
  755. return decimal
  756. } else {
  757. let doubleValue = try unbox(value, as: Double.self)!
  758. return Decimal(doubleValue)
  759. }
  760. }
  761. func unbox<T: Decodable>(_ value: Any, as _: T.Type) throws -> T? {
  762. if T.self == Date.self || T.self == NSDate.self {
  763. guard let date = try self.unbox(value, as: Date.self) else { return nil }
  764. return (date as! T)
  765. }
  766. if T.self == Data.self || T.self == NSData.self {
  767. guard let data = try self.unbox(value, as: Data.self) else { return nil }
  768. return (data as! T)
  769. }
  770. if T.self == URL.self || T.self == NSURL.self {
  771. guard let urlString = try self.unbox(value, as: String.self) else {
  772. return nil
  773. }
  774. guard let url = URL(string: urlString) else {
  775. throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath,
  776. debugDescription: "Invalid URL string."))
  777. }
  778. return (url as! T)
  779. }
  780. if T.self == Decimal.self || T.self == NSDecimalNumber.self {
  781. guard let decimal = try self.unbox(value, as: Decimal.self) else { return nil }
  782. return (decimal as! T)
  783. }
  784. if let v = value as? T {
  785. if isFirestorePassthroughType(v) {
  786. // All the native Firestore types that should not be encoded
  787. return (value as! T)
  788. }
  789. }
  790. // Decoding an embedded container, this requires expanding the storage stack and
  791. // then restore after decoding.
  792. storage.push(container: value)
  793. let decoded = try T(from: self)
  794. storage.popContainer()
  795. return decoded
  796. }
  797. }
  798. extension DecodingError {
  799. static func _typeMismatch(at path: [CodingKey], expectation: Any.Type, reality: Any) -> DecodingError {
  800. let description = "Expected to decode \(expectation) but found \(_typeDescription(of: reality)) instead."
  801. return .typeMismatch(expectation, Context(codingPath: path, debugDescription: description))
  802. }
  803. fileprivate static func _typeDescription(of value: Any) -> String {
  804. if value is NSNull {
  805. return "a null value"
  806. } 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 */ {
  807. return "a number"
  808. } else if value is String {
  809. return "a string/data"
  810. } else if value is [Any] {
  811. return "an array"
  812. } else if value is [String: Any] {
  813. return "a dictionary"
  814. } else {
  815. return "\(type(of: value))"
  816. }
  817. }
  818. }