diff --git a/Example/Firebase.xcodeproj/xcshareddata/xcschemes/FDLBuilderTestAppObjCEarlGrey.xcscheme b/Example/Firebase.xcodeproj/xcshareddata/xcschemes/FDLBuilderTestAppObjCEarlGrey.xcscheme index af5583c4a78..22feddbc9f9 100644 --- a/Example/Firebase.xcodeproj/xcshareddata/xcschemes/FDLBuilderTestAppObjCEarlGrey.xcscheme +++ b/Example/Firebase.xcodeproj/xcshareddata/xcschemes/FDLBuilderTestAppObjCEarlGrey.xcscheme @@ -7,8 +7,11 @@ buildImplicitDependencies = "YES"> + buildForProfiling = "YES" + buildForArchiving = "YES" + buildForAnalyzing = "YES"> + + + + + + + + @@ -49,6 +71,15 @@ debugDocumentVersioning = "YES" debugServiceExtension = "internal" allowLocationSimulation = "YES"> + + + + @@ -58,6 +89,15 @@ savedToolIdentifier = "" useCustomWorkingDirectory = "NO" debugDocumentVersioning = "YES"> + + + + diff --git a/FirebaseFirestoreSwift.podspec b/FirebaseFirestoreSwift.podspec index 684307065f7..d6b3fd69171 100644 --- a/FirebaseFirestoreSwift.podspec +++ b/FirebaseFirestoreSwift.podspec @@ -5,7 +5,7 @@ Pod::Spec.new do |s| s.name = 'FirebaseFirestoreSwift' - s.version = '0.1' + s.version = '0.2.0' s.summary = 'Google Cloud Firestore for iOS Swift Extensions' s.description = <<-DESC diff --git a/Firestore/Example/Firestore.xcodeproj/project.pbxproj b/Firestore/Example/Firestore.xcodeproj/project.pbxproj index 0f49daf6717..f1a0030be46 100644 --- a/Firestore/Example/Firestore.xcodeproj/project.pbxproj +++ b/Firestore/Example/Firestore.xcodeproj/project.pbxproj @@ -229,10 +229,13 @@ DE03B2D61F2149D600A30B9C /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6003F58D195388D20070C39A /* Foundation.framework */; }; DE03B2DD1F2149D600A30B9C /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 6003F5B8195388D20070C39A /* InfoPlist.strings */; }; DE03B3631F215E1A00A30B9C /* CAcert.pem in Resources */ = {isa = PBXBuildFile; fileRef = DE03B3621F215E1600A30B9C /* CAcert.pem */; }; + DE26C61621C15FCC00DE141A /* CodableDocumentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DE26C61521C15FCC00DE141A /* CodableDocumentTests.swift */; }; DE2EF0851F3D0B6E003D0CDC /* FSTArraySortedDictionaryTests.m in Sources */ = {isa = PBXBuildFile; fileRef = DE2EF07E1F3D0B6E003D0CDC /* FSTArraySortedDictionaryTests.m */; }; DE2EF0861F3D0B6E003D0CDC /* FSTImmutableSortedDictionary+Testing.m in Sources */ = {isa = PBXBuildFile; fileRef = DE2EF0801F3D0B6E003D0CDC /* FSTImmutableSortedDictionary+Testing.m */; }; DE2EF0871F3D0B6E003D0CDC /* FSTImmutableSortedSet+Testing.m in Sources */ = {isa = PBXBuildFile; fileRef = DE2EF0821F3D0B6E003D0CDC /* FSTImmutableSortedSet+Testing.m */; }; DE2EF0881F3D0B6E003D0CDC /* FSTTreeSortedDictionaryTests.m in Sources */ = {isa = PBXBuildFile; fileRef = DE2EF0841F3D0B6E003D0CDC /* FSTTreeSortedDictionaryTests.m */; }; + DE84BBB421C18F060048A176 /* FSTAPIHelpers.mm in Sources */ = {isa = PBXBuildFile; fileRef = 5492E04E202154AA00B64F25 /* FSTAPIHelpers.mm */; }; + DE84BBB921C1A6ED0048A176 /* FSTHelpers.mm in Sources */ = {isa = PBXBuildFile; fileRef = 5492E03A2021401F00B64F25 /* FSTHelpers.mm */; }; EBFC611B1BF195D0EC710AF4 /* app_testing.mm in Sources */ = {isa = PBXBuildFile; fileRef = 5467FB07203E6A44009C9584 /* app_testing.mm */; }; /* End PBXBuildFile section */ @@ -545,6 +548,8 @@ DE03B2E91F2149D600A30B9C /* Firestore_IntegrationTests_iOS.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = Firestore_IntegrationTests_iOS.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; DE03B3621F215E1600A30B9C /* CAcert.pem */ = {isa = PBXFileReference; lastKnownFileType = text; path = CAcert.pem; sourceTree = ""; }; DE0761F61F2FE68D003233AF /* BasicCompileTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BasicCompileTests.swift; sourceTree = ""; }; + DE26C61521C15FCC00DE141A /* CodableDocumentTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CodableDocumentTests.swift; sourceTree = ""; }; + DE2EF07E1F3D0B6E003D0CDC /* FSTArraySortedDictionaryTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = FSTArraySortedDictionaryTests.m; path = ../../third_party/Immutable/Tests/FSTArraySortedDictionaryTests.m; sourceTree = ""; }; DE2EF07F1F3D0B6E003D0CDC /* FSTImmutableSortedDictionary+Testing.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "FSTImmutableSortedDictionary+Testing.h"; path = "../../third_party/Immutable/Tests/FSTImmutableSortedDictionary+Testing.h"; sourceTree = ""; }; DE2EF0801F3D0B6E003D0CDC /* FSTImmutableSortedDictionary+Testing.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "FSTImmutableSortedDictionary+Testing.m"; path = "../../third_party/Immutable/Tests/FSTImmutableSortedDictionary+Testing.m"; sourceTree = ""; }; @@ -557,6 +562,7 @@ DE51B1981F0D48AC0013853F /* FSTSpecTests.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = FSTSpecTests.h; sourceTree = ""; }; DE51B19A1F0D48AC0013853F /* FSTSyncEngineTestDriver.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = FSTSyncEngineTestDriver.h; sourceTree = ""; }; DE51B1A71F0D48AC0013853F /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; + DE84BBB821C1951E0048A176 /* BridgingHeader.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = BridgingHeader.h; sourceTree = ""; }; E592181BFD7C53C305123739 /* Pods-Firestore_Tests_iOS.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Firestore_Tests_iOS.debug.xcconfig"; path = "Pods/Target Support Files/Pods-Firestore_Tests_iOS/Pods-Firestore_Tests_iOS.debug.xcconfig"; sourceTree = ""; }; ECEBABC7E7B693BE808A1052 /* Pods_Firestore_IntegrationTests_iOS.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Firestore_IntegrationTests_iOS.framework; sourceTree = BUILT_PRODUCTS_DIR; }; ED4B3E3EA0EBF3ED19A07060 /* grpc_stream_tester.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = grpc_stream_tester.h; sourceTree = ""; }; @@ -757,6 +763,7 @@ 5495EB012040E90200EBA509 /* Codable */ = { isa = PBXGroup; children = ( + DE26C61521C15FCC00DE141A /* CodableDocumentTests.swift */, 5495EB022040E90200EBA509 /* CodableGeoPointTests.swift */, ); path = Codable; @@ -779,6 +786,7 @@ 544A20ED20F6C046004E52CD /* API */, 5495EB012040E90200EBA509 /* Codable */, 54C9EDF52040E16300A969CD /* Info.plist */, + DE84BBB821C1951E0048A176 /* BridgingHeader.h */, ); name = SwiftTests; path = ../Swift/Tests; @@ -1399,6 +1407,7 @@ TargetAttributes = { 54C9EDF02040E16300A969CD = { CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1010; ProvisioningStyle = Automatic; TestTargetID = 6003F589195388D20070C39A; }; @@ -1831,8 +1840,11 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + DE84BBB921C1A6ED0048A176 /* FSTHelpers.mm in Sources */, 544A20EE20F6C10C004E52CD /* BasicCompileTests.swift in Sources */, 5495EB032040E90200EBA509 /* CodableGeoPointTests.swift in Sources */, + DE84BBB421C18F060048A176 /* FSTAPIHelpers.mm in Sources */, + DE26C61621C15FCC00DE141A /* CodableDocumentTests.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -2138,6 +2150,11 @@ ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu11; GCC_NO_COMMON_BLOCKS = YES; + HEADER_SEARCH_PATHS = ( + "$(inherited)", + "\"${PODS_ROOT}/../../..\"", + "\"${PODS_ROOT}/../../../Firestore/third_party/abseil-cpp\"", + ); INFOPLIST_FILE = ../Swift/Tests/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 11.2; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; @@ -2145,8 +2162,9 @@ PRODUCT_BUNDLE_IDENTIFIER = "com.google.Firestore-SwiftTests-iOS"; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OBJC_BRIDGING_HEADER = ../Swift/Tests/BridgingHeader.h; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 4.0; + SWIFT_VERSION = 4.2; TARGETED_DEVICE_FAMILY = "1,2"; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Firestore_Example_iOS.app/Firestore_Example_iOS"; }; @@ -2177,14 +2195,20 @@ ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu11; GCC_NO_COMMON_BLOCKS = YES; + HEADER_SEARCH_PATHS = ( + "$(inherited)", + "\"${PODS_ROOT}/../../..\"", + "\"${PODS_ROOT}/../../../Firestore/third_party/abseil-cpp\"", + ); INFOPLIST_FILE = ../Swift/Tests/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 11.2; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MTL_ENABLE_DEBUG_INFO = NO; PRODUCT_BUNDLE_IDENTIFIER = "com.google.Firestore-SwiftTests-iOS"; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = ../Swift/Tests/BridgingHeader.h; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; - SWIFT_VERSION = 4.0; + SWIFT_VERSION = 4.2; TARGETED_DEVICE_FAMILY = "1,2"; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Firestore_Example_iOS.app/Firestore_Example_iOS"; }; diff --git a/Firestore/Example/Firestore.xcodeproj/xcshareddata/xcschemes/Firestore_Example_iOS.xcscheme b/Firestore/Example/Firestore.xcodeproj/xcshareddata/xcschemes/Firestore_Example_iOS.xcscheme index 8390f30fd00..5190072c475 100644 --- a/Firestore/Example/Firestore.xcodeproj/xcshareddata/xcschemes/Firestore_Example_iOS.xcscheme +++ b/Firestore/Example/Firestore.xcodeproj/xcshareddata/xcschemes/Firestore_Example_iOS.xcscheme @@ -48,6 +48,16 @@ ReferencedContainer = "container:Firestore.xcodeproj"> + + + + -#import "Firestore/Example/Tests/Util/FSTHelpers.h" - -#include "absl/strings/string_view.h" - @class FIRCollectionReference; @class FIRDocumentReference; @class FIRDocumentSnapshot; @class FIRFirestore; @class FIRQuerySnapshot; +/** Allow tests to just use an int literal for versions. */ +typedef int64_t FSTTestSnapshotVersion; + NS_ASSUME_NONNULL_BEGIN #if __cplusplus @@ -36,17 +35,17 @@ extern "C" { FIRFirestore *FSTTestFirestore(); /** A convenience method for creating a doc snapshot for tests. */ -FIRDocumentSnapshot *FSTTestDocSnapshot(const absl::string_view path, +FIRDocumentSnapshot *FSTTestDocSnapshot(const char *path, FSTTestSnapshotVersion version, NSDictionary *_Nullable data, BOOL hasMutations, BOOL fromCache); /** A convenience method for creating a collection reference from a path string. */ -FIRCollectionReference *FSTTestCollectionRef(const absl::string_view path); +FIRCollectionReference *FSTTestCollectionRef(const char *path); /** A convenience method for creating a document reference from a path string. */ -FIRDocumentReference *FSTTestDocRef(const absl::string_view path); +FIRDocumentReference *FSTTestDocRef(const char *path); /** * A convenience method for creating a particular query snapshot for tests. @@ -63,7 +62,7 @@ FIRDocumentReference *FSTTestDocRef(const absl::string_view path); * @returns A query snapshot that consists of both sets of documents. */ FIRQuerySnapshot *FSTTestQuerySnapshot( - const absl::string_view path, + const char *path, NSDictionary *> *oldDocs, NSDictionary *> *docsToAdd, BOOL hasPendingWrites, diff --git a/Firestore/Example/Tests/API/FSTAPIHelpers.mm b/Firestore/Example/Tests/API/FSTAPIHelpers.mm index 8e783c364b2..1ea4993bf78 100644 --- a/Firestore/Example/Tests/API/FSTAPIHelpers.mm +++ b/Firestore/Example/Tests/API/FSTAPIHelpers.mm @@ -22,6 +22,7 @@ #include +#import "Firestore/Example/Tests/Util/FSTHelpers.h" #import "Firestore/Source/API/FIRCollectionReference+Internal.h" #import "Firestore/Source/API/FIRDocumentReference+Internal.h" #import "Firestore/Source/API/FIRDocumentSnapshot+Internal.h" @@ -59,7 +60,7 @@ return sharedInstance; } -FIRDocumentSnapshot *FSTTestDocSnapshot(const absl::string_view path, +FIRDocumentSnapshot *FSTTestDocSnapshot(const char *path, FSTTestSnapshotVersion version, NSDictionary *_Nullable data, BOOL hasMutations, @@ -75,19 +76,19 @@ hasPendingWrites:hasMutations]; } -FIRCollectionReference *FSTTestCollectionRef(const absl::string_view path) { +FIRCollectionReference *FSTTestCollectionRef(const char *path) { return [FIRCollectionReference referenceWithPath:testutil::Resource(path) firestore:FSTTestFirestore()]; } -FIRDocumentReference *FSTTestDocRef(const absl::string_view path) { +FIRDocumentReference *FSTTestDocRef(const char *path) { return [FIRDocumentReference referenceWithPath:testutil::Resource(path) firestore:FSTTestFirestore()]; } /** A convenience method for creating a query snapshots for tests. */ FIRQuerySnapshot *FSTTestQuerySnapshot( - const absl::string_view path, + const char *path, NSDictionary *> *oldDocs, NSDictionary *> *docsToAdd, BOOL hasPendingWrites, diff --git a/Firestore/Swift/Source/Codable/CodableErrors.swift b/Firestore/Swift/Source/Codable/CodableErrors.swift new file mode 100644 index 00000000000..63d76622d86 --- /dev/null +++ b/Firestore/Swift/Source/Codable/CodableErrors.swift @@ -0,0 +1,23 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +enum FirestoreDecodingError: Error { + case decodingIsNotSupported +} + +enum FirestoreEncodingError: Error { + case encodingIsNotSupported +} diff --git a/Firestore/Swift/Source/Codable/DocumentReference+Codable.swift b/Firestore/Swift/Source/Codable/DocumentReference+Codable.swift new file mode 100644 index 00000000000..395e5ba6b89 --- /dev/null +++ b/Firestore/Swift/Source/Codable/DocumentReference+Codable.swift @@ -0,0 +1,39 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import FirebaseFirestore + +/** + * A protocol describing the encodable properties of a DocumentReference. + * + * Note: this protocol exists as a workaround for the Swift compiler: if the DocumentReference class was + * extended directly to conform to Codable, the methods implementing the protcol would be need to be + * marked required but that can't be done in an extension. Declaring the extension on the protocol + * sidesteps this issue. + */ +fileprivate protocol CodableDocumentReference: Codable {} + +extension CodableDocumentReference { + public init(from decoder: Decoder) throws { + throw FirestoreDecodingError.decodingIsNotSupported + } + + public func encode(to encoder: Encoder) throws { + throw FirestoreEncodingError.encodingIsNotSupported + } +} + +extension DocumentReference: CodableDocumentReference {} diff --git a/Firestore/Swift/Source/Codable/FieldValue+Codable.swift b/Firestore/Swift/Source/Codable/FieldValue+Codable.swift new file mode 100644 index 00000000000..9f72c94f16a --- /dev/null +++ b/Firestore/Swift/Source/Codable/FieldValue+Codable.swift @@ -0,0 +1,35 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import FirebaseFirestore + +/** + * A protocol describing the encodable properties of a FirebaseFirestore. + * + * Note: this protocol exists as a workaround for the Swift compiler: if the FieldValue class was + * extended directly to conform to Codable, the methods implementing the protcol would be need to be + * marked required but that can't be done in an extension. Declaring the extension on the protocol + * sidesteps this issue. + */ +fileprivate protocol CodableFieldValue: Encodable {} + +extension CodableFieldValue { + public func encode(to encoder: Encoder) throws { + throw FirestoreEncodingError.encodingIsNotSupported + } +} + +extension FieldValue: CodableFieldValue {} diff --git a/Firestore/Swift/Source/Codable/FirestoreDecoder.swift b/Firestore/Swift/Source/Codable/FirestoreDecoder.swift new file mode 100644 index 00000000000..095efddac54 --- /dev/null +++ b/Firestore/Swift/Source/Codable/FirestoreDecoder.swift @@ -0,0 +1,1062 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Foundation +import FirebaseFirestore + +// Add CollectionReference? + +extension DocumentSnapshot { + public func data(as type: T.Type) throws -> T { + guard let dict = data() else { + throw DecodingError.valueNotFound(T.self, DecodingError.Context(codingPath: [], debugDescription: "Data was empty")) + } + return try Firestore.Decoder().decode(T.self, from: dict) + } +} + +// Is there a better way to do this without the Firestore.Decoder wrapper? + +extension Firestore { + struct Decoder { + func decode(_ type: T.Type, from container: [String: Any]) throws -> T { + let decoder = _FirestoreDecoder(referencing: container) + guard let value = try decoder.unbox(container, as: T.self) else { + throw DecodingError.valueNotFound(T.self, DecodingError.Context(codingPath: [], debugDescription: "The given dictionary was invalid")) + } + + return value + } + } +} + +class _FirestoreDecoder: Decoder { + /// Options set on the top-level encoder to pass down the decoding hierarchy. + + // MARK: Properties + + /// The decoder's storage. + + fileprivate var storage: _FirestoreDecodingStorage + + /// The path to the current point in encoding. + public fileprivate(set) var codingPath: [CodingKey] + + /// Contextual user-provided information for use during encoding. + public var userInfo: [CodingUserInfoKey: Any] = [:] + + // MARK: - Initialization + + /// Initializes `self` with the given top-level container and options. + init(referencing container: Any, at codingPath: [CodingKey] = []) { + storage = _FirestoreDecodingStorage() + storage.push(container: container) + self.codingPath = codingPath + } + + // MARK: - Decoder Methods + + public func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer { + guard !(storage.topContainer is NSNull) else { + throw DecodingError.valueNotFound(KeyedDecodingContainer.self, + DecodingError.Context(codingPath: codingPath, + debugDescription: "Cannot get keyed decoding container -- found null value instead.")) + } + + guard let topContainer = self.storage.topContainer as? [String: Any] else { + let context = DecodingError.Context(codingPath: codingPath, debugDescription: "Not a dictionary") + throw DecodingError.typeMismatch([String: Any].self, context) + } + + let container = _FirestoreKeyedDecodingContainer(referencing: self, wrapping: topContainer) + return KeyedDecodingContainer(container) + } + + public func unkeyedContainer() throws -> UnkeyedDecodingContainer { + guard !(storage.topContainer is NSNull) else { + throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, + DecodingError.Context(codingPath: codingPath, + debugDescription: "Cannot get unkeyed decoding container -- found null value instead.")) + } + + guard let topContainer = self.storage.topContainer as? [Any] else { + let context = DecodingError.Context(codingPath: codingPath, debugDescription: "Not an array") + throw DecodingError.typeMismatch([Any].self, context) + } + + return _FirestoreUnkeyedDecodingContainer(referencing: self, wrapping: topContainer) + } + + public func singleValueContainer() throws -> SingleValueDecodingContainer { + return self + } +} + +fileprivate struct _FirestoreDecodingStorage { + // MARK: Properties + + /// The container stack. + /// Elements may be any one of the plist types (NSNumber, Date, String, Array, [String : Any]). + fileprivate private(set) var containers: [Any] = [] + + // MARK: - Initialization + + /// Initializes `self` with no containers. + fileprivate init() {} + + // MARK: - Modifying the Stack + + fileprivate var count: Int { + return containers.count + } + + fileprivate var topContainer: Any { + precondition(containers.count > 0, "Empty container stack.") + return containers.last! + } + + fileprivate mutating func push(container: Any) { + containers.append(container) + } + + fileprivate mutating func popContainer() { + precondition(containers.count > 0, "Empty container stack.") + containers.removeLast() + } +} + +fileprivate struct _FirestoreKeyedDecodingContainer: KeyedDecodingContainerProtocol { + typealias Key = K + + // MARK: Properties + + /// A reference to the decoder we're reading from. + private let decoder: _FirestoreDecoder + + /// A reference to the container we're reading from. + private let container: [String: Any] + + /// The path of coding keys taken to get to this point in decoding. + public private(set) var codingPath: [CodingKey] + + // MARK: - Initialization + + /// Initializes `self` by referencing the given decoder and container. + fileprivate init(referencing decoder: _FirestoreDecoder, wrapping container: [String: Any]) { + self.decoder = decoder + self.container = container + codingPath = decoder.codingPath + } + + // MARK: - KeyedDecodingContainerProtocol Methods + + public var allKeys: [Key] { + return container.keys.compactMap { Key(stringValue: $0) } + } + + public func contains(_ key: Key) -> Bool { + return container[key.stringValue] != nil + } + + public func decodeNil(forKey key: Key) throws -> Bool { + let entry = try require(key: key) + return entry is NSNull + } + + public func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { + let entry = try require(key: key) + + decoder.codingPath.append(key) + defer { self.decoder.codingPath.removeLast() } + + let value = try decoder.unbox(entry, as: Bool.self) + return try require(value: value) + } + + public func decode(_ type: Int.Type, forKey key: Key) throws -> Int { + let entry = try require(key: key) + + decoder.codingPath.append(key) + defer { self.decoder.codingPath.removeLast() } + + let value = try decoder.unbox(entry, as: Int.self) + return try require(value: value) + } + + public func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { + let entry = try require(key: key) + + decoder.codingPath.append(key) + defer { self.decoder.codingPath.removeLast() } + + let value = try decoder.unbox(entry, as: Int8.self) + return try require(value: value) + } + + public func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { + let entry = try require(key: key) + + decoder.codingPath.append(key) + defer { self.decoder.codingPath.removeLast() } + + let value = try decoder.unbox(entry, as: Int16.self) + return try require(value: value) + } + + public func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { + let entry = try require(key: key) + + decoder.codingPath.append(key) + defer { self.decoder.codingPath.removeLast() } + + let value = try decoder.unbox(entry, as: Int32.self) + return try require(value: value) + } + + public func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { + let entry = try require(key: key) + + decoder.codingPath.append(key) + defer { self.decoder.codingPath.removeLast() } + + let value = try decoder.unbox(entry, as: Int64.self) + return try require(value: value) + } + + public func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { + let entry = try require(key: key) + + decoder.codingPath.append(key) + defer { self.decoder.codingPath.removeLast() } + + let value = try decoder.unbox(entry, as: UInt.self) + return try require(value: value) + } + + public func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { + let entry = try require(key: key) + + decoder.codingPath.append(key) + defer { self.decoder.codingPath.removeLast() } + + let value = try decoder.unbox(entry, as: UInt8.self) + return try require(value: value) + } + + public func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { + let entry = try require(key: key) + + decoder.codingPath.append(key) + defer { self.decoder.codingPath.removeLast() } + + let value = try decoder.unbox(entry, as: UInt16.self) + return try require(value: value) + } + + public func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { + let entry = try require(key: key) + + decoder.codingPath.append(key) + defer { self.decoder.codingPath.removeLast() } + + let value = try decoder.unbox(entry, as: UInt32.self) + return try require(value: value) + } + + public func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { + let entry = try require(key: key) + + decoder.codingPath.append(key) + defer { self.decoder.codingPath.removeLast() } + + let value = try decoder.unbox(entry, as: UInt64.self) + return try require(value: value) + } + + public func decode(_ type: Float.Type, forKey key: Key) throws -> Float { + let entry = try require(key: key) + + decoder.codingPath.append(key) + defer { self.decoder.codingPath.removeLast() } + + let value = try decoder.unbox(entry, as: Float.self) + return try require(value: value) + } + + public func decode(_ type: Double.Type, forKey key: Key) throws -> Double { + let entry = try require(key: key) + + decoder.codingPath.append(key) + defer { self.decoder.codingPath.removeLast() } + + let value = try decoder.unbox(entry, as: Double.self) + return try require(value: value) + } + + public func decode(_ type: String.Type, forKey key: Key) throws -> String { + let entry = try require(key: key) + + decoder.codingPath.append(key) + defer { self.decoder.codingPath.removeLast() } + + let value = try decoder.unbox(entry, as: String.self) + return try require(value: value) + } + + public func decode(_ type: T.Type, forKey key: Key) throws -> T { + let entry = try require(key: key) + + decoder.codingPath.append(key) + defer { self.decoder.codingPath.removeLast() } + + let value = try decoder.unbox(entry, as: T.self) + return try require(value: value) + } + + private func require(key: Key) throws -> Any { + if let entry = self.container[key.stringValue] { + return entry + } + + let description = "No value associated with key \(key) (\"\(key.stringValue)\")." + let context = DecodingError.Context(codingPath: decoder.codingPath, debugDescription: description) + throw DecodingError.keyNotFound(key, context) + } + + private func require(value: T?) throws -> T { + if let value = value { + return value + } + + let message = "Expected \(T.self) value but found null instead." + let context = DecodingError.Context(codingPath: decoder.codingPath, debugDescription: message) + throw DecodingError.valueNotFound(T.self, context) + } + + public func nestedContainer(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer { + decoder.codingPath.append(key) + defer { self.decoder.codingPath.removeLast() } + + guard let value = self.container[key.stringValue] else { + throw DecodingError.valueNotFound(KeyedDecodingContainer.self, + DecodingError.Context(codingPath: codingPath, + debugDescription: "Cannot get nested keyed container -- no value found for key \"\(key.stringValue)\"")) + } + + guard let dictionary = value as? [String: Any] else { + throw DecodingError._typeMismatch(at: codingPath, expectation: [String: Any].self, reality: value) + } + + let container = _FirestoreKeyedDecodingContainer(referencing: decoder, wrapping: dictionary) + return KeyedDecodingContainer(container) + } + + public func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { + decoder.codingPath.append(key) + defer { self.decoder.codingPath.removeLast() } + + guard let value = self.container[key.stringValue] else { + throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, + DecodingError.Context(codingPath: codingPath, + debugDescription: "Cannot get nested unkeyed container -- no value found for key \"\(key.stringValue)\"")) + } + + guard let array = value as? [Any] else { + let context = DecodingError.Context(codingPath: codingPath, debugDescription: "Not an array") + throw DecodingError.typeMismatch([Any].self, context) + } + + return _FirestoreUnkeyedDecodingContainer(referencing: decoder, wrapping: array) + } + + private func _superDecoder(forKey key: CodingKey) throws -> Decoder { + decoder.codingPath.append(key) + defer { self.decoder.codingPath.removeLast() } + + let value: Any = container[key.stringValue] ?? NSNull() + return _FirestoreDecoder(referencing: value, at: decoder.codingPath) + } + + public func superDecoder() throws -> Decoder { + return try _superDecoder(forKey: _FirestoreKey.super) + } + + public func superDecoder(forKey key: Key) throws -> Decoder { + return try _superDecoder(forKey: key) + } +} + +fileprivate struct _FirestoreUnkeyedDecodingContainer: UnkeyedDecodingContainer { + // MARK: Properties + + /// A reference to the decoder we're reading from. + private let decoder: _FirestoreDecoder + + /// A reference to the container we're reading from. + private let container: [Any] + + /// The path of coding keys taken to get to this point in decoding. + public private(set) var codingPath: [CodingKey] + + /// The index of the element we're about to decode. + public private(set) var currentIndex: Int + + // MARK: - Initialization + + /// Initializes `self` by referencing the given decoder and container. + fileprivate init(referencing decoder: _FirestoreDecoder, wrapping container: [Any]) { + self.decoder = decoder + self.container = container + codingPath = decoder.codingPath + currentIndex = 0 + } + + // MARK: - UnkeyedDecodingContainer Methods + + public var count: Int? { + return container.count + } + + public var isAtEnd: Bool { + return currentIndex >= count! + } + + public mutating func decodeNil() throws -> Bool { + try expectNotAtEnd() + + if container[currentIndex] is NSNull { + currentIndex += 1 + return true + } else { + return false + } + } + + public mutating func decode(_ type: Bool.Type) throws -> Bool { + try expectNotAtEnd() + + decoder.codingPath.append(_FirestoreKey(index: currentIndex)) + defer { decoder.codingPath.removeLast() } + + let decoded = try decoder.unbox(container[currentIndex], as: Bool.self) + return try require(value: decoded) + } + + public mutating func decode(_ type: Int.Type) throws -> Int { + try expectNotAtEnd() + + decoder.codingPath.append(_FirestoreKey(index: currentIndex)) + defer { decoder.codingPath.removeLast() } + + let decoded = try decoder.unbox(container[currentIndex], as: Int.self) + return try require(value: decoded) + } + + public mutating func decode(_ type: Int8.Type) throws -> Int8 { + try expectNotAtEnd() + + decoder.codingPath.append(_FirestoreKey(index: currentIndex)) + defer { decoder.codingPath.removeLast() } + + let decoded = try decoder.unbox(container[currentIndex], as: Int8.self) + return try require(value: decoded) + } + + public mutating func decode(_ type: Int16.Type) throws -> Int16 { + try expectNotAtEnd() + + decoder.codingPath.append(_FirestoreKey(index: currentIndex)) + defer { decoder.codingPath.removeLast() } + + let decoded = try decoder.unbox(container[currentIndex], as: Int16.self) + return try require(value: decoded) + } + + public mutating func decode(_ type: Int32.Type) throws -> Int32 { + try expectNotAtEnd() + + decoder.codingPath.append(_FirestoreKey(index: currentIndex)) + defer { decoder.codingPath.removeLast() } + + let decoded = try decoder.unbox(container[currentIndex], as: Int32.self) + return try require(value: decoded) + } + + public mutating func decode(_ type: Int64.Type) throws -> Int64 { + try expectNotAtEnd() + + decoder.codingPath.append(_FirestoreKey(index: currentIndex)) + defer { decoder.codingPath.removeLast() } + + let decoded = try decoder.unbox(container[currentIndex], as: Int64.self) + return try require(value: decoded) + } + + public mutating func decode(_ type: UInt.Type) throws -> UInt { + try expectNotAtEnd() + + decoder.codingPath.append(_FirestoreKey(index: currentIndex)) + defer { decoder.codingPath.removeLast() } + + let decoded = try decoder.unbox(container[currentIndex], as: UInt.self) + return try require(value: decoded) + } + + public mutating func decode(_ type: UInt8.Type) throws -> UInt8 { + try expectNotAtEnd() + + decoder.codingPath.append(_FirestoreKey(index: currentIndex)) + defer { decoder.codingPath.removeLast() } + + let decoded = try decoder.unbox(container[currentIndex], as: UInt8.self) + return try require(value: decoded) + } + + public mutating func decode(_ type: UInt16.Type) throws -> UInt16 { + try expectNotAtEnd() + + decoder.codingPath.append(_FirestoreKey(index: currentIndex)) + defer { self.decoder.codingPath.removeLast() } + + let decoded = try decoder.unbox(container[currentIndex], as: UInt16.self) + return try require(value: decoded) + } + + public mutating func decode(_ type: UInt32.Type) throws -> UInt32 { + try expectNotAtEnd() + + decoder.codingPath.append(_FirestoreKey(index: currentIndex)) + defer { decoder.codingPath.removeLast() } + + let decoded = try decoder.unbox(container[currentIndex], as: UInt32.self) + return try require(value: decoded) + } + + public mutating func decode(_ type: UInt64.Type) throws -> UInt64 { + try expectNotAtEnd() + + decoder.codingPath.append(_FirestoreKey(index: currentIndex)) + defer { decoder.codingPath.removeLast() } + + let decoded = try decoder.unbox(container[currentIndex], as: UInt64.self) + return try require(value: decoded) + } + + public mutating func decode(_ type: Float.Type) throws -> Float { + try expectNotAtEnd() + + decoder.codingPath.append(_FirestoreKey(index: currentIndex)) + defer { self.decoder.codingPath.removeLast() } + + let decoded = try decoder.unbox(container[currentIndex], as: Float.self) + return try require(value: decoded) + } + + public mutating func decode(_ type: Double.Type) throws -> Double { + try expectNotAtEnd() + + decoder.codingPath.append(_FirestoreKey(index: currentIndex)) + defer { self.decoder.codingPath.removeLast() } + + let decoded = try decoder.unbox(container[currentIndex], as: Double.self) + return try require(value: decoded) + } + + public mutating func decode(_ type: String.Type) throws -> String { + try expectNotAtEnd() + + decoder.codingPath.append(_FirestoreKey(index: currentIndex)) + defer { self.decoder.codingPath.removeLast() } + + let decoded = try decoder.unbox(container[currentIndex], as: String.self) + return try require(value: decoded) + } + + public mutating func decode(_ type: T.Type) throws -> T { + try expectNotAtEnd() + + decoder.codingPath.append(_FirestoreKey(index: currentIndex)) + defer { self.decoder.codingPath.removeLast() } + + let decoded = try decoder.unbox(container[currentIndex], as: T.self) + return try require(value: decoded) + } + + public mutating func nestedContainer(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer { + decoder.codingPath.append(_FirestoreKey(index: currentIndex)) + defer { self.decoder.codingPath.removeLast() } + + try expectNotAtEnd() + + let value = self.container[self.currentIndex] + try requireNotNSNull(value) + + guard let dictionary = value as? [String: Any] else { + throw DecodingError._typeMismatch(at: codingPath, expectation: [String: Any].self, reality: value) + } + + currentIndex += 1 + let container = _FirestoreKeyedDecodingContainer(referencing: decoder, wrapping: dictionary) + return KeyedDecodingContainer(container) + } + + public mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer { + decoder.codingPath.append(_FirestoreKey(index: currentIndex)) + defer { self.decoder.codingPath.removeLast() } + + try expectNotAtEnd() + + let value = container[self.currentIndex] + try requireNotNSNull(value) + + guard let array = value as? [Any] else { + throw DecodingError._typeMismatch(at: codingPath, expectation: [Any].self, reality: value) + } + + currentIndex += 1 + return _FirestoreUnkeyedDecodingContainer(referencing: decoder, wrapping: array) + } + + public mutating func superDecoder() throws -> Decoder { + decoder.codingPath.append(_FirestoreKey(index: currentIndex)) + defer { self.decoder.codingPath.removeLast() } + + try expectNotAtEnd() + + let value = container[self.currentIndex] + currentIndex += 1 + return _FirestoreDecoder(referencing: value, at: decoder.codingPath) + } + + private func expectNotAtEnd() throws { + guard !isAtEnd else { + throw DecodingError.valueNotFound(Any?.self, DecodingError.Context(codingPath: decoder.codingPath + [_FirestoreKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) + } + } + + private func requireNotNSNull(_ value: Any) throws { + if !(value is NSNull) { + return + } + + let description = "Cannot get keyed decoding container -- found null value instead." + let context = DecodingError.Context(codingPath: codingPath, debugDescription: description) + throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, context) + } + + private mutating func require(value: T?) throws -> T { + guard let value = value else { + let message = "Expected \(T.self) value but found null instead." + let context = DecodingError.Context(codingPath: decoder.codingPath + [_FirestoreKey(index: currentIndex)], debugDescription: message) + throw DecodingError.valueNotFound(T.self, context) + } + + currentIndex += 1 + return value + } +} + +extension _FirestoreDecoder: SingleValueDecodingContainer { + // MARK: SingleValueDecodingContainer Methods + + private func expectNonNull(_ type: T.Type) throws { + guard !decodeNil() else { + throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) but found null value instead.")) + } + } + + public func decodeNil() -> Bool { + return storage.topContainer is NSNull + } + + public func decode(_ type: Bool.Type) throws -> Bool { + try expectNonNull(Bool.self) + return try unbox(storage.topContainer, as: Bool.self)! + } + + public func decode(_ type: Int.Type) throws -> Int { + try expectNonNull(Int.self) + return try unbox(storage.topContainer, as: Int.self)! + } + + public func decode(_ type: Int8.Type) throws -> Int8 { + try expectNonNull(Int8.self) + return try unbox(storage.topContainer, as: Int8.self)! + } + + public func decode(_ type: Int16.Type) throws -> Int16 { + try expectNonNull(Int16.self) + return try unbox(storage.topContainer, as: Int16.self)! + } + + public func decode(_ type: Int32.Type) throws -> Int32 { + try expectNonNull(Int32.self) + return try unbox(storage.topContainer, as: Int32.self)! + } + + public func decode(_ type: Int64.Type) throws -> Int64 { + try expectNonNull(Int64.self) + return try unbox(storage.topContainer, as: Int64.self)! + } + + public func decode(_ type: UInt.Type) throws -> UInt { + try expectNonNull(UInt.self) + return try unbox(storage.topContainer, as: UInt.self)! + } + + public func decode(_ type: UInt8.Type) throws -> UInt8 { + try expectNonNull(UInt8.self) + return try unbox(storage.topContainer, as: UInt8.self)! + } + + public func decode(_ type: UInt16.Type) throws -> UInt16 { + try expectNonNull(UInt16.self) + return try unbox(storage.topContainer, as: UInt16.self)! + } + + public func decode(_ type: UInt32.Type) throws -> UInt32 { + try expectNonNull(UInt32.self) + return try unbox(storage.topContainer, as: UInt32.self)! + } + + public func decode(_ type: UInt64.Type) throws -> UInt64 { + try expectNonNull(UInt64.self) + return try unbox(storage.topContainer, as: UInt64.self)! + } + + public func decode(_ type: Float.Type) throws -> Float { + try expectNonNull(Float.self) + return try unbox(storage.topContainer, as: Float.self)! + } + + public func decode(_ type: Double.Type) throws -> Double { + try expectNonNull(Double.self) + return try unbox(storage.topContainer, as: Double.self)! + } + + public func decode(_ type: String.Type) throws -> String { + try expectNonNull(String.self) + return try unbox(storage.topContainer, as: String.self)! + } + + public func decode(_ type: T.Type) throws -> T { + try expectNonNull(T.self) + return try unbox(storage.topContainer, as: T.self)! + } +} + +extension _FirestoreDecoder { + /// Returns the given value unboxed from a container. + func unbox(_ value: Any, as type: Bool.Type) throws -> Bool? { + guard !(value is NSNull) else { return nil } + + if let number = value as? NSNumber { + // TODO: Add a flag to coerce non-boolean numbers into Bools? + if number === kCFBooleanTrue as NSNumber { + return true + } else if number === kCFBooleanFalse as NSNumber { + return false + } + + /* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested: + } else if let bool = value as? Bool { + return bool + */ + } + + throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value) + } + + func unbox(_ value: Any, as type: Int.Type) throws -> Int? { + guard !(value is NSNull) else { return nil } + + guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { + throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value) + } + + let int = number.intValue + guard NSNumber(value: int) == number else { + throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Decoded number <\(number)> does not fit in \(type).")) + } + + return int + } + + func unbox(_ value: Any, as type: Int8.Type) throws -> Int8? { + guard !(value is NSNull) else { return nil } + + guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { + throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value) + } + + let int8 = number.int8Value + guard NSNumber(value: int8) == number else { + throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Decoded number <\(number)> does not fit in \(type).")) + } + + return int8 + } + + func unbox(_ value: Any, as type: Int16.Type) throws -> Int16? { + guard !(value is NSNull) else { return nil } + + guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { + throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value) + } + + let int16 = number.int16Value + guard NSNumber(value: int16) == number else { + throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Decoded number <\(number)> does not fit in \(type).")) + } + + return int16 + } + + func unbox(_ value: Any, as type: Int32.Type) throws -> Int32? { + guard !(value is NSNull) else { return nil } + + guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { + throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value) + } + + let int32 = number.int32Value + guard NSNumber(value: int32) == number else { + throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Decoded number <\(number)> does not fit in \(type).")) + } + + return int32 + } + + func unbox(_ value: Any, as type: Int64.Type) throws -> Int64? { + guard !(value is NSNull) else { return nil } + + guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { + throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value) + } + + let int64 = number.int64Value + guard NSNumber(value: int64) == number else { + throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Decoded number <\(number)> does not fit in \(type).")) + } + + return int64 + } + + func unbox(_ value: Any, as type: UInt.Type) throws -> UInt? { + guard !(value is NSNull) else { return nil } + + guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { + throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value) + } + + let uint = number.uintValue + guard NSNumber(value: uint) == number else { + throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Decoded number <\(number)> does not fit in \(type).")) + } + + return uint + } + + func unbox(_ value: Any, as type: UInt8.Type) throws -> UInt8? { + guard !(value is NSNull) else { return nil } + + guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { + throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value) + } + + let uint8 = number.uint8Value + guard NSNumber(value: uint8) == number else { + throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Decoded number <\(number)> does not fit in \(type).")) + } + + return uint8 + } + + func unbox(_ value: Any, as type: UInt16.Type) throws -> UInt16? { + guard !(value is NSNull) else { return nil } + + guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { + throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value) + } + + let uint16 = number.uint16Value + guard NSNumber(value: uint16) == number else { + throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Decoded number <\(number)> does not fit in \(type).")) + } + + return uint16 + } + + func unbox(_ value: Any, as type: UInt32.Type) throws -> UInt32? { + guard !(value is NSNull) else { return nil } + + guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { + throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value) + } + + let uint32 = number.uint32Value + guard NSNumber(value: uint32) == number else { + throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Decoded number <\(number)> does not fit in \(type).")) + } + + return uint32 + } + + func unbox(_ value: Any, as type: UInt64.Type) throws -> UInt64? { + guard !(value is NSNull) else { return nil } + + guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { + throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value) + } + + let uint64 = number.uint64Value + guard NSNumber(value: uint64) == number else { + throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Decoded number <\(number)> does not fit in \(type).")) + } + + return uint64 + } + + func unbox(_ value: Any, as type: Float.Type) throws -> Float? { + guard !(value is NSNull) else { return nil } + + if let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse { + // We are willing to return a Float by losing precision: + // * If the original value was integral, + // * and the integral value was > Float.greatestFiniteMagnitude, we will fail + // * and the integral value was <= Float.greatestFiniteMagnitude, we are willing to lose precision past 2^24 + // * If it was a Float, you will get back the precise value + // * If it was a Double or Decimal, you will get back the nearest approximation if it will fit + let double = number.doubleValue + guard abs(double) <= Double(Float.greatestFiniteMagnitude) else { + throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "Decoded number \(number) does not fit in \(type).")) + } + + return Float(double) + + /* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested: + } else if let double = value as? Double { + if abs(double) <= Double(Float.max) { + return Float(double) + } + overflow = true + } else if let int = value as? Int { + if let float = Float(exactly: int) { + return float + } + overflow = true + */ + } + + throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value) + } + + func unbox(_ value: Any, as type: Double.Type) throws -> Double? { + guard !(value is NSNull) else { return nil } + + if let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse { + // We are always willing to return the number as a Double: + // * 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 + // * If it was a Float or Double, you will get back the precise value + // * If it was Decimal, you will get back the nearest approximation + return number.doubleValue + + /* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested: + } else if let double = value as? Double { + return double + } else if let int = value as? Int { + if let double = Double(exactly: int) { + return double + } + overflow = true + */ + } + + throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value) + } + + func unbox(_ value: Any, as type: String.Type) throws -> String? { + guard !(value is NSNull) else { return nil } + + guard let string = value as? String else { + throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value) + } + + return string + } + + func unbox(_ value: Any, as type: Date.Type) throws -> Date? { + guard !(value is NSNull) else { return nil } + guard let date = value as? Date else { + throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value) + } + return date + } + + func unbox(_ value: Any, as type: Data.Type) throws -> Data? { + guard !(value is NSNull) else { return nil } + guard let data = value as? Data else { + throw DecodingError._typeMismatch(at: codingPath, expectation: type, reality: value) + } + return data + } + + func unbox(_ value: Any, as type: Decimal.Type) throws -> Decimal? { + guard !(value is NSNull) else { return nil } + + // Attempt to bridge from NSDecimalNumber. + if let decimal = value as? Decimal { + return decimal + } else { + let doubleValue = try unbox(value, as: Double.self)! + return Decimal(doubleValue) + } + } + + func unbox(_ value: Any, as type: T.Type) throws -> T? { + let decoded: T + if T.self == Date.self || T.self == NSDate.self { + guard let date = try self.unbox(value, as: Date.self) else { return nil } + decoded = date as! T + } else if T.self == Data.self || T.self == NSData.self { + guard let data = try self.unbox(value, as: Data.self) else { return nil } + decoded = data as! T + } else if T.self == URL.self || T.self == NSURL.self { + guard let urlString = try self.unbox(value, as: String.self) else { + return nil + } + + guard let url = URL(string: urlString) else { + throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, + debugDescription: "Invalid URL string.")) + } + + decoded = (url as! T) + } else if T.self == Decimal.self || T.self == NSDecimalNumber.self { + guard let decimal = try self.unbox(value, as: Decimal.self) else { return nil } + decoded = decimal as! T + } else if T.self == GeoPoint.self || T.self == DocumentReference.self { + // All the native types that should not be encoded + decoded = value as! T + } else { + storage.push(container: value) + decoded = try T(from: self) + storage.popContainer() + } + + return decoded + } +} diff --git a/Firestore/Swift/Source/Codable/FirestoreEncoder.swift b/Firestore/Swift/Source/Codable/FirestoreEncoder.swift new file mode 100644 index 00000000000..eba68545af8 --- /dev/null +++ b/Firestore/Swift/Source/Codable/FirestoreEncoder.swift @@ -0,0 +1,612 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Foundation +import FirebaseFirestore + +extension CollectionReference { + public func addDocument(_ item: T) throws -> DocumentReference { + do { + return addDocument(data: try Firestore.Encoder().encode(item)) + } catch let error { + throw (error) + } + } + + public func addDocument(_ item: T, _ completion: ((Error?) -> Void)?) throws -> DocumentReference { + do { + let encoded = try Firestore.Encoder().encode(item) + return addDocument(data: encoded, completion: completion) + } catch let error { + throw (error) + } + } +} + +extension DocumentReference { + public func setData(value: T) throws { + do { + setData(try Firestore.Encoder().encode(value)) + } catch let error { + throw (error) + } + } + + public func setData(value: T, _ completion: ((Error?) -> Void)?) throws { + do { + let encoded = try Firestore.Encoder().encode(value) + setData(encoded, completion: completion) + } catch let error { + throw error + } + } +} + +extension Transaction { + public func setData(value: T, forDocument: DocumentReference) throws { + do { + setData(try Firestore.Encoder().encode(value), forDocument: forDocument) + } catch let error { + throw (error) + } + } +} + +extension WriteBatch { + public func setData(value: T, forDocument: DocumentReference) throws { + do { + setData(try Firestore.Encoder().encode(value), forDocument: forDocument) + } catch let error { + throw (error) + } + } +} + +extension Firestore { + struct Encoder { + func encode(_ value: T) throws -> [String: Any] { + guard let topLevel = try _FirestoreEncoder().box_(value) else { + throw EncodingError.invalidValue(value, + EncodingError.Context(codingPath: [], + debugDescription: "Top-level \(T.self) did not encode any values.")) + } + + // This is O(n) check. We might get rid of it once we refactor to internal + guard let dict = topLevel as? [String: Any] else { + throw EncodingError.invalidValue(value, + EncodingError.Context(codingPath: [], + debugDescription: "Top-level \(T.self) encoded not as dictionary.")) + } + + return dict + } + } +} + +fileprivate class _FirestoreEncoder: Encoder { + fileprivate var storage: _FirestoreEncodingStorage + public fileprivate(set) var codingPath: [CodingKey] + public var userInfo: [CodingUserInfoKey: Any] = [:] + + init(codingPath: [CodingKey] = []) { + storage = _FirestoreEncodingStorage() + self.codingPath = codingPath + } + + /// Returns whether a new element can be encoded at this coding path. + /// + /// `true` if an element has not yet been encoded at this coding path; `false` otherwise. + fileprivate var canEncodeNewValue: Bool { + // 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). + // At the same time, every time a container is requested, a new value gets pushed onto the storage stack. + // 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. + // + // This means that anytime something that can request a new container goes onto the stack, we MUST push a key onto the coding path. + // 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). + return storage.count == codingPath.count + } + + // MARK: - Encoder Methods + + public func container(keyedBy: Key.Type) -> KeyedEncodingContainer { + // If an existing keyed container was already requested, return that one. + let topContainer: NSMutableDictionary + if canEncodeNewValue { + // We haven't yet pushed a container at this level; do so here. + topContainer = storage.pushKeyedContainer() + } else { + guard let container = self.storage.containers.last as? NSMutableDictionary else { + preconditionFailure("Attempt to push new keyed encoding container when already previously encoded at this path.") + } + + topContainer = container + } + + let container = _FirestoreKeyedEncodingContainer(referencing: self, codingPath: codingPath, wrapping: topContainer) + return KeyedEncodingContainer(container) + } + + public func unkeyedContainer() -> UnkeyedEncodingContainer { + // If an existing unkeyed container was already requested, return that one. + let topContainer: NSMutableArray + if canEncodeNewValue { + // We haven't yet pushed a container at this level; do so here. + topContainer = storage.pushUnkeyedContainer() + } else { + guard let container = self.storage.containers.last as? NSMutableArray else { + preconditionFailure("Attempt to push new unkeyed encoding container when already previously encoded at this path.") + } + + topContainer = container + } + + return _FirestoreUnkeyedEncodingContainer(referencing: self, codingPath: codingPath, wrapping: topContainer) + } + + public func singleValueContainer() -> SingleValueEncodingContainer { + return self + } +} + +fileprivate struct _FirestoreEncodingStorage { + // MARK: Properties + + /// The container stack. + /// Elements may be any one of the plist types (NSNumber, NSString, NSDate, NSArray, NSDictionary). + fileprivate private(set) var containers: [NSObject] = [] + + // MARK: - Initialization + + /// Initializes `self` with no containers. + fileprivate init() {} + + // MARK: - Modifying the Stack + + fileprivate var count: Int { + return containers.count + } + + fileprivate mutating func pushKeyedContainer() -> NSMutableDictionary { + let dictionary = NSMutableDictionary() + containers.append(dictionary) + return dictionary + } + + fileprivate mutating func pushUnkeyedContainer() -> NSMutableArray { + let array = NSMutableArray() + containers.append(array) + return array + } + + fileprivate mutating func push(container: NSObject) { + containers.append(container) + } + + fileprivate mutating func popContainer() -> NSObject { + precondition(containers.count > 0, "Empty container stack.") + return containers.popLast()! + } +} + +fileprivate struct _FirestoreKeyedEncodingContainer: KeyedEncodingContainerProtocol { + typealias Key = K + + // MARK: Properties + + /// A reference to the encoder we're writing to. + private let encoder: _FirestoreEncoder + + /// A reference to the container we're writing to. + private let container: NSMutableDictionary + + /// The path of coding keys taken to get to this point in encoding. + public private(set) var codingPath: [CodingKey] + + // MARK: - Initialization + + /// Initializes `self` with the given references. + fileprivate init(referencing encoder: _FirestoreEncoder, codingPath: [CodingKey], wrapping container: NSMutableDictionary) { + self.encoder = encoder + self.codingPath = codingPath + self.container = container + } + + // MARK: - KeyedEncodingContainerProtocol Methods + + public mutating func encodeNil(forKey key: Key) throws { container[key.stringValue] = NSNull() } + public mutating func encode(_ value: Bool, forKey key: Key) throws { container[key.stringValue] = encoder.box(value) } + public mutating func encode(_ value: Int, forKey key: Key) throws { container[key.stringValue] = encoder.box(value) } + public mutating func encode(_ value: Int8, forKey key: Key) throws { container[key.stringValue] = encoder.box(value) } + public mutating func encode(_ value: Int16, forKey key: Key) throws { container[key.stringValue] = encoder.box(value) } + public mutating func encode(_ value: Int32, forKey key: Key) throws { container[key.stringValue] = encoder.box(value) } + public mutating func encode(_ value: Int64, forKey key: Key) throws { container[key.stringValue] = encoder.box(value) } + public mutating func encode(_ value: UInt, forKey key: Key) throws { container[key.stringValue] = encoder.box(value) } + public mutating func encode(_ value: UInt8, forKey key: Key) throws { container[key.stringValue] = encoder.box(value) } + public mutating func encode(_ value: UInt16, forKey key: Key) throws { container[key.stringValue] = encoder.box(value) } + public mutating func encode(_ value: UInt32, forKey key: Key) throws { container[key.stringValue] = encoder.box(value) } + public mutating func encode(_ value: UInt64, forKey key: Key) throws { container[key.stringValue] = encoder.box(value) } + public mutating func encode(_ value: String, forKey key: Key) throws { container[key.stringValue] = encoder.box(value) } + public mutating func encode(_ value: Float, forKey key: Key) throws { container[key.stringValue] = encoder.box(value) } + public mutating func encode(_ value: Double, forKey key: Key) throws { container[key.stringValue] = encoder.box(value) } + + public mutating func encode(_ value: T, forKey key: Key) throws { + encoder.codingPath.append(key) + defer { encoder.codingPath.removeLast() } + container[key.stringValue] = try encoder.box(value) + } + + public mutating func nestedContainer(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer { + let dictionary = NSMutableDictionary() + self.container[key.stringValue] = dictionary + + codingPath.append(key) + defer { codingPath.removeLast() } + + let container = _FirestoreKeyedEncodingContainer(referencing: encoder, codingPath: codingPath, wrapping: dictionary) + return KeyedEncodingContainer(container) + } + + public mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { + let array = NSMutableArray() + container[key.stringValue] = array + + codingPath.append(key) + defer { codingPath.removeLast() } + return _FirestoreUnkeyedEncodingContainer(referencing: encoder, codingPath: codingPath, wrapping: array) + } + + public mutating func superEncoder() -> Encoder { + return _FirestoreReferencingEncoder(referencing: encoder, at: _FirestoreKey.super, wrapping: container) + } + + public mutating func superEncoder(forKey key: Key) -> Encoder { + return _FirestoreReferencingEncoder(referencing: encoder, at: key, wrapping: container) + } +} + +fileprivate struct _FirestoreUnkeyedEncodingContainer: UnkeyedEncodingContainer { + // MARK: Properties + + /// A reference to the encoder we're writing to. + private let encoder: _FirestoreEncoder + + /// A reference to the container we're writing to. + private let container: NSMutableArray + + /// The path of coding keys taken to get to this point in encoding. + public private(set) var codingPath: [CodingKey] + + /// The number of elements encoded into the container. + public var count: Int { + return container.count + } + + // MARK: - Initialization + + /// Initializes `self` with the given references. + fileprivate init(referencing encoder: _FirestoreEncoder, codingPath: [CodingKey], wrapping container: NSMutableArray) { + self.encoder = encoder + self.codingPath = codingPath + self.container = container + } + + // MARK: - UnkeyedEncodingContainer Methods + + public mutating func encodeNil() throws { container.add(NSNull()) } + public mutating func encode(_ value: Bool) throws { container.add(encoder.box(value)) } + public mutating func encode(_ value: Int) throws { container.add(encoder.box(value)) } + public mutating func encode(_ value: Int8) throws { container.add(encoder.box(value)) } + public mutating func encode(_ value: Int16) throws { container.add(encoder.box(value)) } + public mutating func encode(_ value: Int32) throws { container.add(encoder.box(value)) } + public mutating func encode(_ value: Int64) throws { container.add(encoder.box(value)) } + public mutating func encode(_ value: UInt) throws { container.add(encoder.box(value)) } + public mutating func encode(_ value: UInt8) throws { container.add(encoder.box(value)) } + public mutating func encode(_ value: UInt16) throws { container.add(encoder.box(value)) } + public mutating func encode(_ value: UInt32) throws { container.add(encoder.box(value)) } + public mutating func encode(_ value: UInt64) throws { container.add(encoder.box(value)) } + public mutating func encode(_ value: Float) throws { container.add(encoder.box(value)) } + public mutating func encode(_ value: Double) throws { container.add(encoder.box(value)) } + public mutating func encode(_ value: String) throws { container.add(encoder.box(value)) } + + public mutating func encode(_ value: T) throws { + encoder.codingPath.append(_FirestoreKey(index: count)) + defer { encoder.codingPath.removeLast() } + container.add(try encoder.box(value)) + } + + public mutating func nestedContainer(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer { + codingPath.append(_FirestoreKey(index: count)) + defer { self.codingPath.removeLast() } + + let dictionary = NSMutableDictionary() + self.container.add(dictionary) + + let container = _FirestoreKeyedEncodingContainer(referencing: encoder, codingPath: codingPath, wrapping: dictionary) + return KeyedEncodingContainer(container) + } + + public mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { + codingPath.append(_FirestoreKey(index: count)) + defer { self.codingPath.removeLast() } + + let array = NSMutableArray() + container.add(array) + return _FirestoreUnkeyedEncodingContainer(referencing: encoder, codingPath: codingPath, wrapping: array) + } + + public mutating func superEncoder() -> Encoder { + return _FirestoreReferencingEncoder(referencing: encoder, at: container.count, wrapping: container) + } +} + +struct _FirestoreKey: CodingKey { + public var stringValue: String + public var intValue: Int? + + public init?(stringValue: String) { + self.stringValue = stringValue + intValue = nil + } + + public init?(intValue: Int) { + stringValue = "\(intValue)" + self.intValue = intValue + } + + init(index: Int) { + stringValue = "Index \(index)" + intValue = index + } + + static let `super` = _FirestoreKey(stringValue: "super")! +} + +extension _FirestoreEncoder { + /// Returns the given value boxed in a container appropriate for pushing onto the container stack. + fileprivate func box(_ value: Bool) -> NSObject { return NSNumber(value: value) } + fileprivate func box(_ value: Int) -> NSObject { return NSNumber(value: value) } + fileprivate func box(_ value: Int8) -> NSObject { return NSNumber(value: value) } + fileprivate func box(_ value: Int16) -> NSObject { return NSNumber(value: value) } + fileprivate func box(_ value: Int32) -> NSObject { return NSNumber(value: value) } + fileprivate func box(_ value: Int64) -> NSObject { return NSNumber(value: value) } + fileprivate func box(_ value: UInt) -> NSObject { return NSNumber(value: value) } + fileprivate func box(_ value: UInt8) -> NSObject { return NSNumber(value: value) } + fileprivate func box(_ value: UInt16) -> NSObject { return NSNumber(value: value) } + fileprivate func box(_ value: UInt32) -> NSObject { return NSNumber(value: value) } + fileprivate func box(_ value: UInt64) -> NSObject { return NSNumber(value: value) } + fileprivate func box(_ value: Float) -> NSObject { return NSNumber(value: value) } + fileprivate func box(_ value: Double) -> NSObject { return NSNumber(value: value) } + fileprivate func box(_ value: String) -> NSObject { return NSString(string: value) } + + fileprivate func box(_ value: T) throws -> NSObject { + return try box_(value) ?? NSDictionary() + } + + func box_(_ value: T) throws -> NSObject? { + if T.self == Date.self || T.self == NSDate.self { + return (value as! NSDate) + } else if T.self == Data.self || T.self == NSData.self { + return (value as! NSData) + } else if T.self == URL.self || T.self == NSURL.self { + return box((value as! URL).absoluteString) + } else if T.self == Decimal.self || T.self == NSDecimalNumber.self { + return (value as! NSDecimalNumber) + } else if T.self == GeoPoint.self || T.self == DocumentReference.self || T.self == FieldValue.self { + // These are all native _Firestore types that we don't need to Encode + return (value as! NSObject) + } + + // The value should request a container from the _FirestoreEncoder. + let depth = storage.count + do { + try value.encode(to: self) + } catch { + // If the value pushed a container before throwing, pop it back off to restore state. + if storage.count > depth { + _ = storage.popContainer() + } + + throw error + } + + // The top container should be a new container. + guard storage.count > depth else { + return nil + } + + return storage.popContainer() + } +} + +extension _FirestoreEncoder: SingleValueEncodingContainer { + // MARK: - SingleValueEncodingContainer Methods + + private func assertCanEncodeNewValue() { + precondition(canEncodeNewValue, "Attempt to encode value through single value container when previously value already encoded.") + } + + public func encodeNil() throws { + assertCanEncodeNewValue() + storage.push(container: NSNull()) + } + + public func encode(_ value: Bool) throws { + assertCanEncodeNewValue() + storage.push(container: box(value)) + } + + public func encode(_ value: Int) throws { + assertCanEncodeNewValue() + storage.push(container: box(value)) + } + + public func encode(_ value: Int8) throws { + assertCanEncodeNewValue() + storage.push(container: box(value)) + } + + public func encode(_ value: Int16) throws { + assertCanEncodeNewValue() + storage.push(container: box(value)) + } + + public func encode(_ value: Int32) throws { + assertCanEncodeNewValue() + storage.push(container: box(value)) + } + + public func encode(_ value: Int64) throws { + assertCanEncodeNewValue() + storage.push(container: box(value)) + } + + public func encode(_ value: UInt) throws { + assertCanEncodeNewValue() + storage.push(container: box(value)) + } + + public func encode(_ value: UInt8) throws { + assertCanEncodeNewValue() + storage.push(container: box(value)) + } + + public func encode(_ value: UInt16) throws { + assertCanEncodeNewValue() + storage.push(container: box(value)) + } + + public func encode(_ value: UInt32) throws { + assertCanEncodeNewValue() + storage.push(container: box(value)) + } + + public func encode(_ value: UInt64) throws { + assertCanEncodeNewValue() + storage.push(container: box(value)) + } + + public func encode(_ value: String) throws { + assertCanEncodeNewValue() + storage.push(container: box(value)) + } + + public func encode(_ value: Float) throws { + assertCanEncodeNewValue() + storage.push(container: box(value)) + } + + public func encode(_ value: Double) throws { + assertCanEncodeNewValue() + storage.push(container: box(value)) + } + + public func encode(_ value: T) throws { + assertCanEncodeNewValue() + try storage.push(container: box(value)) + } +} + +fileprivate class _FirestoreReferencingEncoder: _FirestoreEncoder { + // MARK: Reference types. + + /// The type of container we're referencing. + private enum Reference { + /// Referencing a specific index in an array container. + case array(NSMutableArray, Int) + + /// Referencing a specific key in a dictionary container. + case dictionary(NSMutableDictionary, String) + } + + // MARK: - Properties + + /// The encoder we're referencing. + private let encoder: _FirestoreEncoder + + /// The container reference itself. + private let reference: Reference + + // MARK: - Initialization + + /// Initializes `self` by referencing the given array container in the given encoder. + fileprivate init(referencing encoder: _FirestoreEncoder, at index: Int, wrapping array: NSMutableArray) { + self.encoder = encoder + reference = .array(array, index) + super.init(codingPath: encoder.codingPath) + + codingPath.append(_FirestoreKey(index: index)) + } + + /// Initializes `self` by referencing the given dictionary container in the given encoder. + fileprivate init(referencing encoder: _FirestoreEncoder, at key: CodingKey, wrapping dictionary: NSMutableDictionary) { + self.encoder = encoder + reference = .dictionary(dictionary, key.stringValue) + super.init(codingPath: encoder.codingPath) + codingPath.append(key) + } + + // MARK: - Coding Path Operations + + fileprivate override var canEncodeNewValue: Bool { + // With a regular encoder, the storage and coding path grow together. + // A referencing encoder, however, inherits its parents coding path, as well as the key it was created for. + // We have to take this into account. + return storage.count == codingPath.count - encoder.codingPath.count - 1 + } + + // MARK: - Deinitialization + + // Finalizes `self` by writing the contents of our storage to the referenced encoder's storage. + deinit { + let value: Any + switch storage.count { + case 0: value = NSDictionary() + case 1: value = self.storage.popContainer() + default: fatalError("Referencing encoder deallocated with multiple containers on stack.") + } + + switch self.reference { + case let .array(array, index): + array.insert(value, at: index) + + case let .dictionary(dictionary, key): + dictionary[NSString(string: key)] = value + } + } +} + +extension DecodingError { + static func _typeMismatch(at path: [CodingKey], expectation: Any.Type, reality: Any) -> DecodingError { + let description = "Expected to decode \(expectation) but found \(_typeDescription(of: reality)) instead." + return .typeMismatch(expectation, Context(codingPath: path, debugDescription: description)) + } + + fileprivate static func _typeDescription(of value: Any) -> String { + if value is NSNull { + return "a null value" + } 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 */ { + return "a number" + } else if value is String { + return "a string/data" + } else if value is [Any] { + return "an array" + } else if value is [String: Any] { + return "a dictionary" + } else { + return "\(type(of: value))" + } + } +} diff --git a/Firestore/Swift/Source/Codable/CodableGeoPoint.swift b/Firestore/Swift/Source/Codable/GeoPoint+Codable.swift similarity index 100% rename from Firestore/Swift/Source/Codable/CodableGeoPoint.swift rename to Firestore/Swift/Source/Codable/GeoPoint+Codable.swift diff --git a/Firestore/Swift/Source/Codable/Timestamp+Codable.swift b/Firestore/Swift/Source/Codable/Timestamp+Codable.swift new file mode 100644 index 00000000000..44896c84fde --- /dev/null +++ b/Firestore/Swift/Source/Codable/Timestamp+Codable.swift @@ -0,0 +1,45 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import FirebaseFirestore + +/** + * A protocol describing the encodable properties of a DocumentSnapshot. + * + * Note: this protocol exists as a workaround for the Swift compiler: if the DocumentSnapshot class was + * extended directly to conform to Codable, the methods implementing the protcol would be need to be + * marked required but that can't be done in an extension. Declaring the extension on the protocol + * sidesteps this issue. + */ +public protocol CodableTimestamp: Codable { + init(date: Date) + func dateValue() -> Date +} + +extension CodableTimestamp { + var date: Date { return dateValue() } + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + self.init(date: try container.decode(Date.self)) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(dateValue()) + } +} + +extension Timestamp: CodableTimestamp {} diff --git a/Firestore/Swift/Tests/BridgingHeader.h b/Firestore/Swift/Tests/BridgingHeader.h new file mode 100644 index 00000000000..d8f451d7b0a --- /dev/null +++ b/Firestore/Swift/Tests/BridgingHeader.h @@ -0,0 +1,22 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BridgingHeader_h +#define BridgingHeader_h + +#import "FSTAPIHelpers.h" + +#endif /* BridgingHeader_h */ diff --git a/Firestore/Swift/Tests/Codable/CodableDocumentTests.swift b/Firestore/Swift/Tests/Codable/CodableDocumentTests.swift new file mode 100644 index 00000000000..3f78632e357 --- /dev/null +++ b/Firestore/Swift/Tests/Codable/CodableDocumentTests.swift @@ -0,0 +1,403 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import FirebaseFirestore +@testable import FirebaseFirestoreSwift +import Foundation +import XCTest + +class CodableDocumentTests: XCTestCase { + func roundTrip(input: X, expected: [String: Any], doTest: Bool = true) -> X where X: Codable { + var encoded = [String: Any]() + do { + encoded = try Firestore.Encoder().encode(input) + if doTest { + XCTAssertEqual(encoded as NSDictionary, expected as NSDictionary) + } + } catch { + XCTFail("Failed to encode \(X.self): error: \(error)") + } + do { + let decoded = try Firestore.Decoder().decode(X.self, from: encoded) + return decoded + } catch { + XCTFail("Failed to decode \(X.self): \(error)") + } + return input // After failure + } + + func testInt() { + struct Model: Codable { + let x: Int + } + let model = Model(x: 42) + let dict = ["x": 42] + XCTAssertEqual(model.x, roundTrip(input: model, expected: dict).x) + } + + func testEmpty() { + struct Model: Codable {} + let model = Model() + let dict = [String: Any]() + XCTAssertEqual((try Firestore.Encoder().encode(model)) as NSDictionary, dict as NSDictionary) + } + + func testNil() { + struct Model: Codable { + let x: Int? + } + let model = Model(x: nil) + let dict = ["x": nil] as [String: Int?] + let encodedDict = try! Firestore.Encoder().encode(model) + XCTAssertNil(encodedDict["x"]) + let model2 = try? Firestore.Decoder().decode(Model.self, from: dict as [String: Any]) + XCTAssertNil(model2) + } + + func testOptional() { + struct Model: Codable { + let x: Int + let opt: Int? + } + let dict = ["x": 42] + let model = Model(x: 42, opt: nil) + XCTAssertEqual(model.x, roundTrip(input: model, expected: dict).x) + + let model2 = Model(x: 42, opt: 7) + let expected = ["x": 42, "opt": 7] + let encoded = try! Firestore.Encoder().encode(model2) + XCTAssertEqual(encoded as NSDictionary, expected as NSDictionary) + let decoded = try! Firestore.Decoder().decode(Model.self, from: expected) + XCTAssertEqual(decoded.x, model2.x) + XCTAssertEqual(decoded.opt, model2.opt) + } + + func testOptionalTimestamp() { + class FirestoreDummy { + /// Partial keypath can represent the property name + func setObject(_ object: T, fieldValues: [PartialKeyPath: FieldValue] = [:]) { + // Encode, check if any timestamps are nil or not, and if so use FieldValue.serverTimestamp() + } + } + struct Model: Codable { + let value: Int + let timestamp: Timestamp? + } + let c = Model(value: 10, timestamp: nil) + let fs = FirestoreDummy() + // If no custom field values need to be set: + fs.setObject(c) + + // Or, overriding custom field values: + fs.setObject(c, fieldValues: [\Model.timestamp: FieldValue.serverTimestamp(), + \Model.value: FieldValue.delete()]) + } + + func testEnum() { + enum MyEnum: Codable, Equatable { + case num(number: Int) + case text(String) + case timestamp(Timestamp) + + private enum CodingKeys: String, CodingKey { + case num + case text + case timestamp + } + + private enum DecodingError: Error { + case decoding(String) + } + + init(from decoder: Decoder) throws { + let values = try decoder.container(keyedBy: CodingKeys.self) + if let value = try? values.decode(Int.self, forKey: .num) { + self = .num(number: value) + return + } + if let value = try? values.decode(String.self, forKey: .text) { + self = .text(value) + return + } + if let value = try? values.decode(Timestamp.self, forKey: .timestamp) { + self = .timestamp(value) + return + } + throw DecodingError.decoding("Decoding error: \(dump(values))") + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + switch self { + case let .num(number): + try container.encode(number, forKey: .num) + case let .text(value): + try container.encode(value, forKey: .text) + case let .timestamp(stamp): + try container.encode(stamp, forKey: .timestamp) + } + } + } + struct Model: Codable { + let x: Int + let e: MyEnum + } + let model = Model(x: 42, e: MyEnum.num(number: 4)) + let output = roundTrip(input: model, expected: [:], doTest: false) + XCTAssertEqual(model.x, output.x) + XCTAssertEqual(model.e, output.e) + + let model2 = Model(x: 43, e: MyEnum.text("abc")) + let output2 = roundTrip(input: model2, expected: [:], doTest: false) + XCTAssertEqual(model2.x, output2.x) + XCTAssertEqual(model2.e, output2.e) + + let model3 = Model(x: 43, e: MyEnum.timestamp(Timestamp(date: Date()))) + let output3 = roundTrip(input: model3, expected: [:], doTest: false) + XCTAssertEqual(model3.x, output3.x) + XCTAssertEqual(model3.e, output3.e) + } + + func testGeoPoint() { + struct Model: Codable { + let p: GeoPoint + } + let model = Model(p: GeoPoint(latitude: 1, longitude: -2)) + let dict = ["p": GeoPoint(latitude: 1, longitude: -2)] + XCTAssertEqual(model.p, roundTrip(input: model, expected: dict).p) + } + + func testDate() { + struct Model: Codable { + let date: Date + } + let d = Date(timeIntervalSinceReferenceDate: 0) + let model = Model(date: d) + let dict = ["date": d] + XCTAssertEqual(model.date, roundTrip(input: model, expected: dict).date) + } + + func testDocumentReference() { + struct Model: Codable { + let doc: DocumentReference + } + let d = FSTTestDocRef("abc/xyz") + let model = Model(doc: d) + let dict = ["doc": d] + XCTAssertEqual(model.doc, roundTrip(input: model, expected: dict).doc) + } + + func testTimestamp() { + struct Model: Codable { + let timestamp: Timestamp + } + let t = Timestamp(date: Date()) + let model = Model(timestamp: t) + let encoded = (try! Firestore.Encoder().encode(model)) + let model2 = try! Firestore.Decoder().decode(Model.self, from: encoded) + XCTAssertEqual(model.timestamp, model2.timestamp) + } + + func testBadValue() { + struct Model: Codable { + let x: Int + } + let dict = ["x": "abc"] + var didThrow = false + do { + _ = try Firestore.Decoder().decode(Model.self, from: dict) + } catch { + didThrow = true + } + XCTAssertTrue(didThrow) + } + + func testValueTooBig() { + struct Model: Codable { + let x: CChar + } + let dict = ["x": 12345] + let model = try? Firestore.Decoder().decode(Model.self, from: dict) + XCTAssertNil(model) + + let dict2 = ["x": 12] + let model2 = try? Firestore.Decoder().decode(Model.self, from: dict2) + XCTAssertNotNil(model2) + } + + // Inspired by https://github.com/firebase/firebase-android-sdk/blob/master/firebase-firestore/src/test/java/com/google/firebase/firestore/util/MapperTest.java + func testBeans() { + struct Model: Codable { + let s: String + let d: Double + let f: Float + let l: CLongLong + let i: Int + let b: Bool + let sh: CShort + let byte: CChar + let uchar: CUnsignedChar + let ai: [Int] + let si: [String] + let caseSensitive: String + let casESensitive: String + let casESensitivE: String + } + let model = Model( + s: "abc", + d: 123, + f: -4.321, + l: 1_234_567_890_123, + i: -4444, + b: false, + sh: 123, + byte: 45, + uchar: 44, + ai: [1, 2, 3, 4], + si: ["abc", "def"], + caseSensitive: "aaa", + casESensitive: "bbb", + casESensitivE: "ccc" + ) + let dict = [ + "s": "abc", + "d": 123, + "f": -4.321, + "l": 1_234_567_890_123, + "i": -4444, + "b": false, + "sh": 123, + "byte": 45, + "uchar": 44, + "ai": [1, 2, 3, 4], + "si": ["abc", "def"], + "caseSensitive": "aaa", + "casESensitive": "bbb", + "casESensitivE": "ccc", + ] as [String: Any] + + let model2 = try! Firestore.Decoder().decode(Model.self, from: dict) + XCTAssertEqual(model.s, model2.s) + XCTAssertEqual(model.d, model2.d) + XCTAssertEqual(model.f, model2.f) + XCTAssertEqual(model.l, model2.l) + XCTAssertEqual(model.i, model2.i) + XCTAssertEqual(model.b, model2.b) + XCTAssertEqual(model.sh, model2.sh) + XCTAssertEqual(model.byte, model2.byte) + XCTAssertEqual(model.uchar, model2.uchar) + XCTAssertEqual(model.ai, model2.ai) + XCTAssertEqual(model.si, model2.si) + XCTAssertEqual(model.caseSensitive, model2.caseSensitive) + XCTAssertEqual(model.casESensitive, model2.casESensitive) + XCTAssertEqual(model.casESensitivE, model2.casESensitivE) + + let encodedDict = try! Firestore.Encoder().encode(model) + XCTAssertEqual(encodedDict["s"] as! String, "abc") + XCTAssertEqual(encodedDict["d"] as! Double, 123) + XCTAssertEqual(encodedDict["f"] as! Float, -4.321) + XCTAssertEqual(encodedDict["l"] as! CLongLong, 1_234_567_890_123) + XCTAssertEqual(encodedDict["i"] as! Int, -4444) + XCTAssertEqual(encodedDict["b"] as! Bool, false) + XCTAssertEqual(encodedDict["sh"] as! CShort, 123) + XCTAssertEqual(encodedDict["byte"] as! CChar, 45) + XCTAssertEqual(encodedDict["uchar"] as! CUnsignedChar, 44) + XCTAssertEqual(encodedDict["ai"] as! [Int], [1, 2, 3, 4]) + XCTAssertEqual(encodedDict["si"] as! [String], ["abc", "def"]) + XCTAssertEqual(encodedDict["caseSensitive"] as! String, "aaa") + XCTAssertEqual(encodedDict["casESensitive"] as! String, "bbb") + XCTAssertEqual(encodedDict["casESensitivE"] as! String, "ccc") + } + + func testCodingKeys() { + struct Model: Codable { + var s: String + var ms: String + var d: Double + var md: Double + var i: Int + var mi: Int + var b: Bool + var mb: Bool + + enum CodingKeys: String, CodingKey { + case s + case d + case i + case b + } + + public init(from decoder: Decoder) throws { + let values = try decoder.container(keyedBy: CodingKeys.self) + s = try values.decode(String.self, forKey: .s) + d = try values.decode(Double.self, forKey: .d) + i = try values.decode(Int.self, forKey: .i) + b = try values.decode(Bool.self, forKey: .b) + ms = "filler" + md = 42.42 + mi = -9 + mb = false + } + + public init(ins: String, inms: String, ind: Double, inmd: Double, ini: Int, inmi: Int, inb: Bool, inmb: Bool) { + s = ins + d = ind + i = ini + b = inb + ms = inms + md = inmd + mi = inmi + mb = inmb + } + } + let model = Model( + ins: "abc", + inms: "dummy", + ind: 123.3, + inmd: 0, + ini: -4444, + inmi: 0, + inb: true, + inmb: true + ) + let dict = [ + "s": "abc", + "d": 123.3, + "i": -4444, + "b": true, + ] as [String: Any] + + let model2 = try! Firestore.Decoder().decode(Model.self, from: dict) + XCTAssertEqual(model.s, model2.s) + XCTAssertEqual(model.d, model2.d) + XCTAssertEqual(model.i, model2.i) + XCTAssertEqual(model.b, model2.b) + XCTAssertEqual(model2.ms, "filler") + XCTAssertEqual(model2.md, 42.42) + XCTAssertEqual(model2.mi, -9) + XCTAssertEqual(model2.mb, false) + + let encodedDict = try! Firestore.Encoder().encode(model) + XCTAssertEqual(encodedDict["s"] as! String, "abc") + XCTAssertEqual(encodedDict["d"] as! Double, 123.3) + XCTAssertEqual(encodedDict["i"] as! Int, -4444) + XCTAssertEqual(encodedDict["b"] as! Bool, true) + XCTAssertNil(encodedDict["ms"]) + XCTAssertNil(encodedDict["md"]) + XCTAssertNil(encodedDict["mi"]) + XCTAssertNil(encodedDict["mb"]) + } +}