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 29a0ab8dd64..d988db48a87 100644 --- a/Firestore/Example/Firestore.xcodeproj/project.pbxproj +++ b/Firestore/Example/Firestore.xcodeproj/project.pbxproj @@ -233,10 +233,14 @@ 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 */; }; + DE65B16F21FFAEA300CC4A09 /* FSTAPIHelpers.mm in Sources */ = {isa = PBXBuildFile; fileRef = 5492E04E202154AA00B64F25 /* FSTAPIHelpers.mm */; }; + DE65B17021FFAECB00CC4A09 /* FSTHelpers.mm in Sources */ = {isa = PBXBuildFile; fileRef = 5492E03A2021401F00B64F25 /* FSTHelpers.mm */; }; + DE958C0521FA82D200E6C1C5 /* CodableTimestampTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DE958C0421FA82D200E6C1C5 /* CodableTimestampTests.swift */; }; EBFC611B1BF195D0EC710AF4 /* app_testing.mm in Sources */ = {isa = PBXBuildFile; fileRef = 5467FB07203E6A44009C9584 /* app_testing.mm */; }; /* End PBXBuildFile section */ @@ -556,6 +560,7 @@ 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 = ""; }; @@ -568,6 +573,8 @@ 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 = ""; }; + DE958C0421FA82D200E6C1C5 /* CodableTimestampTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CodableTimestampTests.swift; sourceTree = ""; }; DF148C0D5EEC4A2CD9FA484C /* Pods-macOS_example.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-macOS_example.release.xcconfig"; path = "Pods/Target Support Files/Pods-macOS_example/Pods-macOS_example.release.xcconfig"; sourceTree = ""; }; E42355285B9EF55ABD785792 /* Pods_macOS_example.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_macOS_example.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 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 = ""; }; @@ -780,7 +787,9 @@ 5495EB012040E90200EBA509 /* Codable */ = { isa = PBXGroup; children = ( + DE26C61521C15FCC00DE141A /* CodableDocumentTests.swift */, 5495EB022040E90200EBA509 /* CodableGeoPointTests.swift */, + DE958C0421FA82D200E6C1C5 /* CodableTimestampTests.swift */, ); path = Codable; sourceTree = ""; @@ -802,6 +811,7 @@ 544A20ED20F6C046004E52CD /* API */, 5495EB012040E90200EBA509 /* Codable */, 54C9EDF52040E16300A969CD /* Info.plist */, + DE84BBB821C1951E0048A176 /* BridgingHeader.h */, ); name = SwiftTests; path = ../Swift/Tests; @@ -1462,6 +1472,7 @@ TargetAttributes = { 54C9EDF02040E16300A969CD = { CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1010; ProvisioningStyle = Automatic; TestTargetID = 6003F589195388D20070C39A; }; @@ -1937,8 +1948,12 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + DE65B16F21FFAEA300CC4A09 /* FSTAPIHelpers.mm in Sources */, + DE65B17021FFAECB00CC4A09 /* FSTHelpers.mm in Sources */, 544A20EE20F6C10C004E52CD /* BasicCompileTests.swift in Sources */, 5495EB032040E90200EBA509 /* CodableGeoPointTests.swift in Sources */, + DE26C61621C15FCC00DE141A /* CodableDocumentTests.swift in Sources */, + DE958C0521FA82D200E6C1C5 /* CodableTimestampTests.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -2259,6 +2274,11 @@ ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = c99; 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"; @@ -2266,8 +2286,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"; }; @@ -2298,14 +2319,20 @@ ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = c99; 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 5f924386c8d..04cdbf15146 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 cfe7b07319d..9de4096a1ac 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" @@ -60,7 +61,7 @@ return sharedInstance; } -FIRDocumentSnapshot *FSTTestDocSnapshot(const absl::string_view path, +FIRDocumentSnapshot *FSTTestDocSnapshot(const char *path, FSTTestSnapshotVersion version, NSDictionary *_Nullable data, BOOL hasMutations, @@ -76,19 +77,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..0b5dcf070ff --- /dev/null +++ b/Firestore/Swift/Source/Codable/CodableErrors.swift @@ -0,0 +1,23 @@ +/* + * Copyright 2019 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. + */ + +public enum FirestoreDecodingError: Error { + case decodingIsNotSupported +} + +public enum FirestoreEncodingError: Error { + case encodingIsNotSupported +} diff --git a/Firestore/Swift/Source/Codable/CodablePassThroughTypes.swift b/Firestore/Swift/Source/Codable/CodablePassThroughTypes.swift new file mode 100644 index 00000000000..d946f8999cf --- /dev/null +++ b/Firestore/Swift/Source/Codable/CodablePassThroughTypes.swift @@ -0,0 +1,24 @@ +/* + * Copyright 2019 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 + +internal func isFirestorePassthroughType(_ value: T) -> Bool { + return + T.self == GeoPoint.self || + T.self == Timestamp.self +} diff --git a/Firestore/Swift/Source/Codable/CodableGeoPoint.swift b/Firestore/Swift/Source/Codable/GeoPoint+Codable.swift similarity index 87% rename from Firestore/Swift/Source/Codable/CodableGeoPoint.swift rename to Firestore/Swift/Source/Codable/GeoPoint+Codable.swift index fa563403c8d..1c422d54a70 100644 --- a/Firestore/Swift/Source/Codable/CodableGeoPoint.swift +++ b/Firestore/Swift/Source/Codable/GeoPoint+Codable.swift @@ -1,5 +1,5 @@ /* - * Copyright 2018 Google + * Copyright 2019 Google * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,10 +19,10 @@ import FirebaseFirestore /** * A protocol describing the encodable properties of a GeoPoint. * - * Note: this protocol exists as a workaround for the Swift compiler: if the GeoPoint 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. + * Note: this protocol exists as a workaround for the Swift compiler: if the GeoPoint class + * was extended directly to conform to Codable, the methods implementing the protocol 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 CodableGeoPoint: Codable { var latitude: Double { get } diff --git a/Firestore/Swift/Source/Codable/Timestamp+Codable.swift b/Firestore/Swift/Source/Codable/Timestamp+Codable.swift new file mode 100644 index 00000000000..1581caaf14d --- /dev/null +++ b/Firestore/Swift/Source/Codable/Timestamp+Codable.swift @@ -0,0 +1,62 @@ +/* + * Copyright 2019 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 Timestamp. + * + * Note: this protocol exists as a workaround for the Swift compiler: if the Timestamp class + * was extended directly to conform to Codable, the methods implementing the protocol 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 CodableTimestamp: Codable { + var seconds: Int64 { get } + var nanoseconds: Int32 { get } + + init(seconds: Int64, nanoseconds: Int32) +} + +/** The keys in a GeoPoint. Must match the properties of CodableGeoPoint. */ +fileprivate enum TimestampKeys: String, CodingKey { + case seconds + case nanoseconds +} + +/** + * An extension of GeoPoint that implements the behavior of the Codable protocol. + * + * Note: this is implemented manually here because the Swift compiler can't synthesize these methods + * when declaring an extension to conform to Codable. + */ +extension CodableTimestamp { + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: TimestampKeys.self) + let seconds = try container.decode(Int64.self, forKey: .seconds) + let nanoseconds = try container.decode(Int32.self, forKey: .nanoseconds) + self.init(seconds: seconds, nanoseconds: nanoseconds) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: TimestampKeys.self) + try container.encode(seconds, forKey: .seconds) + try container.encode(nanoseconds, forKey: .nanoseconds) + } +} + +/** Extends GeoPoint to conform to Codable. */ +extension Timestamp: CodableTimestamp {} diff --git a/Firestore/Swift/Source/Codable/third_party/FirestoreDecoder.swift b/Firestore/Swift/Source/Codable/third_party/FirestoreDecoder.swift new file mode 100644 index 00000000000..bbc1f7beee5 --- /dev/null +++ b/Firestore/Swift/Source/Codable/third_party/FirestoreDecoder.swift @@ -0,0 +1,1020 @@ +// This file is derived from swift/stdlib/public/SDK/Foundation/JSONEncoder.swift +// and swift/stdlib/public/SDK/Foundation/PlistEncoder.swift + +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +import Foundation +import FirebaseFirestore + +extension Firestore { + public struct Decoder { + public init() {} + public 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 + } + } + + 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) + } + + 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 + } + + 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? { + if T.self == Date.self || T.self == NSDate.self { + guard let date = try self.unbox(value, as: Date.self) else { return nil } + return (date as! T) + } + if T.self == Data.self || T.self == NSData.self { + guard let data = try self.unbox(value, as: Data.self) else { return nil } + return (data as! T) + } + 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.")) + } + return (url as! T) + } + if T.self == Decimal.self || T.self == NSDecimalNumber.self { + guard let decimal = try self.unbox(value, as: Decimal.self) else { return nil } + return (decimal as! T) + } + if let v = value as? T { + if isFirestorePassthroughType(v) { + // All the native Firestore types that should not be encoded + return (value as! T) + } + } + storage.push(container: value) + let decoded = try T(from: self) + storage.popContainer() + return decoded + } +} diff --git a/Firestore/Swift/Source/Codable/third_party/FirestoreEncoder.swift b/Firestore/Swift/Source/Codable/third_party/FirestoreEncoder.swift new file mode 100644 index 00000000000..6b4c9b1410a --- /dev/null +++ b/Firestore/Swift/Source/Codable/third_party/FirestoreEncoder.swift @@ -0,0 +1,553 @@ +// This file is derived from swift/stdlib/public/SDK/Foundation/JSONEncoder.swift +// and swift/stdlib/public/SDK/Foundation/PlistEncoder.swift + +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +import Foundation +import FirebaseFirestore + +extension Firestore { + public struct Encoder { + public init() {} + public 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. Consider refactoring box_ to return [String: Any]. + 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 isFirestorePassthroughType(value) { + // This is a 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/Tests/API/BasicCompileTests.swift b/Firestore/Swift/Tests/API/BasicCompileTests.swift index 0889979c94e..628196e4cb7 100644 --- a/Firestore/Swift/Tests/API/BasicCompileTests.swift +++ b/Firestore/Swift/Tests/API/BasicCompileTests.swift @@ -198,7 +198,7 @@ func writeDocuments(at docRef: DocumentReference, database db: Firestore) { } func addDocument(to collectionRef: CollectionReference) { - collectionRef.addDocument(data: ["foo": 42]) + _ = collectionRef.addDocument(data: ["foo": 42]) // or collectionRef.document().setData(["foo": 42]) } diff --git a/Firestore/Swift/Tests/BridgingHeader.h b/Firestore/Swift/Tests/BridgingHeader.h new file mode 100644 index 00000000000..7becc83f2e7 --- /dev/null +++ b/Firestore/Swift/Tests/BridgingHeader.h @@ -0,0 +1,22 @@ +/* + * Copyright 2019 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..ec6b7c331db --- /dev/null +++ b/Firestore/Swift/Tests/Codable/CodableDocumentTests.swift @@ -0,0 +1,376 @@ +/* + * Copyright 2019 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 +@testable import FirebaseFirestoreSwift +import XCTest + +fileprivate func assertRoundTrip(model: X, encoded: [String: Any]) -> Void { + let enc = assertEncodes(model, encoded: encoded) + assertDecodes(enc, encoded: model) +} + +fileprivate func assertEncodes(_ model: X, encoded: [String: Any]) -> [String: Any] { + do { + let enc = try Firestore.Encoder().encode(model) + XCTAssertEqual(enc as NSDictionary, encoded as NSDictionary) + return enc + } catch { + XCTFail("Failed to encode \(X.self): error: \(error)") + } + return ["": -1] +} + +fileprivate func assertDecodes(_ model: [String: Any], encoded: X) -> Void { + do { + let decoded = try Firestore.Decoder().decode(X.self, from: model) + XCTAssertEqual(decoded, encoded) + } catch { + XCTFail("Failed to decode \(X.self): \(error)") + } +} + +fileprivate func assertDecodingThrows(_ model: [String: Any], encoded: X) -> Void { + do { + _ = try Firestore.Decoder().decode(X.self, from: model) + } catch { + return + } + XCTFail("Failed to throw") +} + +class CodableDocumentTests: XCTestCase { + func testInt() { + struct Model: Codable, Equatable { + let x: Int + } + let model = Model(x: 42) + let dict = ["x": 42] + assertRoundTrip(model: model, encoded: dict) + } + + func testEmpty() { + struct Model: Codable, Equatable {} + _ = assertEncodes(Model(), encoded: [String: Any]()) + } + + func testNil() { + struct Model: Codable, Equatable { + 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 testIntNilString() { + struct Model: Codable, Equatable { + let i: Int + let x: Int? + let s: String + } + let model = Model(i: 7, x: nil, s: "abc") + let encodedDict = try! Firestore.Encoder().encode(model) + XCTAssertNil(encodedDict["x"]) + XCTAssertTrue(encodedDict.keys.contains("i")) + + // TODO: - handle encoding keys with nil values + // See https://stackoverflow.com/questions/47266862/encode-nil-value-as-null-with-jsonencoder + // and https://bugs.swift.org/browse/SR-9232 + // XCTAssertTrue(encodedDict.keys.contains("x")) + } + + func testOptional() { + struct Model: Codable, Equatable { + let x: Int + let opt: Int? + } + assertRoundTrip(model: Model(x: 42, opt: nil), encoded: ["x": 42]) + assertRoundTrip(model: Model(x: 42, opt: 7), encoded: ["x": 42, "opt": 7]) + assertDecodes(["x": 42, "opt": 5], encoded: Model(x: 42, opt: 5)) + assertDecodingThrows(["x": 42, "opt": true], encoded: Model(x: 42, opt: nil)) + assertDecodingThrows(["x": 42, "opt": "abc"], encoded: Model(x: 42, opt: nil)) + assertDecodingThrows(["x": 45.55, "opt": 5], encoded: Model(x: 42, opt: nil)) + assertDecodingThrows(["opt": 5], encoded: Model(x: 42, opt: nil)) + } + + 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, Equatable { + let x: Int + let e: MyEnum + } + + let model = Model(x: 42, e: MyEnum.num(number: 4)) + assertRoundTrip(model: model, encoded: ["x": 42, "e": ["num": 4]]) + let model2 = Model(x: 43, e: MyEnum.text("abc")) + assertRoundTrip(model: model2, encoded: ["x": 43, "e": ["text": "abc"]]) + let timestamp = Timestamp(date: Date()) + let model3 = Model(x: 43, e: MyEnum.timestamp(timestamp)) + assertRoundTrip(model: model3, encoded: ["x": 43, "e": ["timestamp": timestamp]]) + } + + func testGeoPoint() { + struct Model: Codable, Equatable { + let p: GeoPoint + } + let geopoint = GeoPoint(latitude: 1, longitude: -2) + let model = Model(p: geopoint) + assertRoundTrip(model: model, encoded: ["p": geopoint]) + } + + func testDate() { + struct Model: Codable, Equatable { + let date: Date + } + let date = Date(timeIntervalSinceReferenceDate: 0) + let model = Model(date: date) + assertRoundTrip(model: model, encoded: ["date": date]) + } + + // Uncomment if we decide to reenable embedded DocumentReference's +// +// func testDocumentReference() { +// struct Model: Codable, Equatable { +// let doc: DocumentReference +// } +// let d = FSTTestDocRef("abc/xyz") +// let model = Model(doc: d) +// assertRoundTrip(model: model, encoded: ["doc": d]) +// } +// +// // DocumentReference is not Codable unless embedded in a Firestore object. +// func testDocumentReferenceEncodes() { +// let doc = FSTTestDocRef("abc/xyz") +// do { +// _ = try JSONEncoder().encode(doc) +// XCTFail("Failed to throw") +// } catch FirebaseFirestoreSwift.FirestoreEncodingError.encodingIsNotSupported { +// return +// } catch { +// XCTFail("Unrecognized error: \(error)") +// } +// } + + func testTimestamp() { + struct Model: Codable, Equatable { + let timestamp: Timestamp + } + let t = Timestamp(date: Date()) + let model = Model(timestamp: t) + assertRoundTrip(model: model, encoded: ["timestamp": t]) + } + + func testBadValue() { + struct Model: Codable, Equatable { + let x: Int + } + let dict = ["x": "abc"] // Wrong type; + let model = Model(x: 42) + assertDecodingThrows(dict, encoded: model) + } + + func testValueTooBig() { + struct Model: Codable, Equatable { + let x: CChar + } + let dict = ["x": 12345] // Overflow + let model = Model(x: 42) + assertDecodingThrows(dict, encoded: model) + assertRoundTrip(model: model, encoded: ["x": 42]) + } + + // 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, Equatable { + 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, + 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, + "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] + + assertRoundTrip(model: model, encoded: dict) + } + + func testCodingKeys() { + struct Model: Codable, Equatable { + var s: String + var ms: String + var d: Double + var md: Double + var i: Int + var mi: Int + var b: Bool + var mb: Bool + + // Use CodingKeys to only encode part of the struct. + 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"]) + } +} diff --git a/Firestore/Swift/Tests/Codable/CodableGeoPointTests.swift b/Firestore/Swift/Tests/Codable/CodableGeoPointTests.swift index 6b1dce432a0..51a99d854ea 100644 --- a/Firestore/Swift/Tests/Codable/CodableGeoPointTests.swift +++ b/Firestore/Swift/Tests/Codable/CodableGeoPointTests.swift @@ -1,5 +1,5 @@ /* - * Copyright 2018 Google + * Copyright 2019 Google * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Firestore/Swift/Tests/Codable/CodableTimestampTests.swift b/Firestore/Swift/Tests/Codable/CodableTimestampTests.swift new file mode 100644 index 00000000000..f59546e26a4 --- /dev/null +++ b/Firestore/Swift/Tests/Codable/CodableTimestampTests.swift @@ -0,0 +1,49 @@ +/* + * Copyright 2019 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 +import FirebaseFirestoreSwift +import Foundation +import XCTest + +class CodableTimestampTests: XCTestCase { + func testTimestampEncodes() { + let timestamp = Timestamp(seconds: 37, nanoseconds: 123) + + let jsonData = try! JSONEncoder().encode(timestamp) + let json = String(data: jsonData, encoding: .utf8)! + + // The ordering of attributes in the JSON output is not guaranteed, nor is the rounding of + // the values so just verify that each required property is present and that the value + // starts as expected. + XCTAssert(json.contains("\"seconds\":37")) + XCTAssert(json.contains("\"nanoseconds\":123")) + } + + func testTimestampDecodes() { + let json = """ + { + "seconds": 37, + "nanoseconds": 122 + } + """ + let jsonData: Data = json.data(using: .utf8)! + + let timestamp = try! JSONDecoder().decode(Timestamp.self, from: jsonData) + XCTAssertEqual(37, timestamp.seconds) + XCTAssertEqual(122, timestamp.nanoseconds) + } +}